jeudi 4 juin 2015

SocketException: Socket is closed. during unit testing

I'm trying to unit test my class.

The class is like

class Manager{

  class Handler extends Thread{
    Socket socket = null;
    BufferedReader in = null;
    public Handler(Socket s){
        socket = s;
        try{
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        catch(IOException e){
            ...
        }
    }
}

}

and have unit test code too, like

@Test
public void testHandler(){
  Socket s = mock(Socket.class);
  Handler h = Manager.new Handler(s);
  InputStream is = new ByteArrayInputStream(new String("Hello").getBytes());

  try {
    when(s.getInputStream()).thenReturn(is);
  } catch (IOException e) {
    e.printStackTrace();
  }

  assertNotNull(h.in);
}

But, I could see an error message. Error was

java.net.SocketException: Socket is closed
  at java.net.Socket.getInputStream(Unknown Source)

at in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Also, my test failed because of java.lang.NullPointerException at Handler h = Manager.new Handler(s);

How can I solve this problem?

Thank you.

Aucun commentaire:

Enregistrer un commentaire