我有一个服务器类,它故意没有传递给它的参数,并希望使用Mockito对其进行测试。
如果你想在Github上查看完整的源代码:
服务器.class
public class Server extends Thread {
private Other other;
ObjectInputStream fromClient;
ObjectOutputStream toClient;
public Server(){
this.other = new Other(foo, bar);
}
@Override
public void run(){
try{
ServerSocket serverSocket = new ServerSocket(1337);
Socket socket = serverSocket.accept();
fromClient = new ObjectInputStream(socket.getInputStream());
toClient = new ObjectOutputStream(socket.getOutputStream());
while(true) {
int command = (Integer) fromClient.readObject();
switch (command) {
case 0x1:
//add
//...
break;
case 0x2:
//get server data
toClient.writeObject(other.getSomething());
break;
case 0x3:
//delete
//...
break;
default:
break;
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t = new Server();
t.start();
}
}
问题
我知道Mockito不能模拟最终类,例如ObjectOutputStream和ObjectInputStream。
这正是我遇到问题的地方。
到目前为止,我的测试在线NullPointerException失败
when(server.fromClient.readObject()).thenReturn(0x2);.
这是 Mockito 的典型情况,当遇到最终方法时。
服务器测试.class
我尝试了什么
在其他文章中有人建议,可以通过实现接口来更改所测试类的签名来规避最终问题,因此无论如何都会模拟它。ObjectInput
然而,在所提出的方法中,当不作为参数传递给被测类时,不清楚如何操作。ObjectOutputStream
另外,当您直接控制一个 的响应时,如何操作,如我的结构所示,这对于 TCP 客户端/服务器应用程序来说并不罕见。ObjectInputStreamObjectOutputStreamcase
到目前为止,我的印象是我的测试可以工作,如果不是签名中的最终关键字。如果我错了,请在这里纠正我。ObjectOutputStream
问:“为什么我不将流传递到服务器?答:因为我在其他任何地方都不需要它们。
这真的是最后的努力,如果有必要,我会的,但我宁愿不这样做。
慕码人2483693
牧羊人nacy
相关分类