我有一个我想测试的代码 -
ServerHello connect(
int version, Collection<Integer> cipherSuites)
{
Socket s = null;
try {
if(proxy!=null) {
s = new Socket(proxy);
}else {
s = new Socket();
}
try {
s.connect(isa);
} catch (IOException ioe) {
System.err.println("could not connect to "
+ isa + ": " + ioe.toString());
return null;
}
byte[] ch = makeClientHello(version, cipherSuites);
OutputRecord orec = new OutputRecord(
s.getOutputStream());
orec.setType(Constants.HANDSHAKE);
orec.setVersion(version);
orec.write(ch);
orec.flush();
ServerHello x = new ServerHello(s.getInputStream());
return x;
} catch (IOException ioe) {
} finally {
try {
s.close();
} catch (IOException ioe) {
// ignored
}
}
return null;
}
我想用自己的 this.socket.getInputStream()
和 this.socket.getOutputStream()
数据。如何设置此数据?
,我也希望o确保this.socket.connect()
在任何测试中通过,而不会在我的测试中丢下任何例外(离线测试)。
我该怎么做?我正在使用Mockito框架进行测试
它相当容易,您只需要以返回自己的流并捕获书面数据的方式来模拟套接字并将模拟方法路由路由:
@RunWith(MockitoJUnitRunner.class)
public class MyTest
{
@Mock
private Socket socket;
@Mock
private OutputStream myOutputStream;
@Captor
private ArgumentCaptor<byte[]> valueCapture;
@Test
public void test01()
{
Mockito.when(socket.getOutputStream()).thenReturn(myOutputStream);
//EXECUTE YOUR TEST LOGIC HERE
Mockito.verify(myOutputStream).write(valueCapture.capture());
byte[] writtenData = valueCapture.getValue();
}
}
我建议您做某种教程,例如:https://www.baeldung.com/mockito-antotations或https://examples.javacodegeeks.com/core-java/core-java/mockito/mockito-tutorior-tutorial-beginners-/