SocketException:Socket已关闭。在单元测试期间

时间:2015-06-05 03:54:55

标签: java sockets unit-testing

我正在尝试对我的班级进行单元测试。

班级就像

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){
                ...
            }
        }
    }
}

也有单位测试代码,比如

@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);
}

但是,我可以看到一条错误消息。 错误是

time, myPackage.Manager$Handler <init>
serious: null
    java.net.SocketException: Socket is closed
    at java.net.Socket.getInputStream(Unknown Source)
    at myPackage.Manager$Handler.<init>(Manager.java:70)
    at myPackage.Manager$SocketServerThread.run(Manager.java:249)

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

我该如何解决这个问题?

谢谢。

1 个答案:

答案 0 :(得分:0)

在设置Socket之前,您已将Handler传递给when(s.getInputStream()).thenReturn(is); 试试这个

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

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

  Handler h = Manager.new Handler(s);

  assertNotNull(h.in);
}