我正在尝试对我的班级进行单元测试。
班级就像
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()));
我该如何解决这个问题?
谢谢。
答案 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);
}