mardi 12 avril 2016

Android: Trying to test sockets

I'm trying to test socket communication in Android Java, but can't seem to get a mock working.

First of all, using Mockito, mock(Socket.class) throws an Exception java.lang.VerifyError.

So I coded my mock like so:

public void testMyTest(){
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    final ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());

    try{
        byte[] buffer = new byte[6];
        os.write("poulet".getBytes());
        is.read(buffer, 0, 6);
        Log.w(LOG_TAG, "Read result:" + (new String(buffer, "UTF-8")));
    } catch(IOException e){}
}

However is is not reading from os when I call os.write(). The raw result is [B@42204320 and, in string form, it looks like ������������. I tried commenting os.write() but nothing changed.

Does anyone know how to link an input stream to read form an output stream?

To test my classes I just called

final Socket mockedSocket1 = new Socket();
final Socket mockedSocket2 = new Socket();
when(mockedSocket1.getInputStream()).thenReturn(is);
when(mockedSocket2.getOutputStream()).thenReturn(os)

So that my classes get the linked output and input streams that I'm going to test with.

Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire