【发布时间】:2020-12-27 13:03:58
【问题描述】:
想就我的单元测试如何关闭套接字和 outputstreamwriter 的方法寻求帮助。目前,我的单元测试能够覆盖的只是抛出异常的部分。
方法如下:
private final void CloseConnection() {
ErrorHandler objErrHdl = new ErrorHandler();
try {
out.close();
clientSocket.close();
} catch ( IOException e ) {
objErrHdl.LogError( this.getClass().getName() , "CloseConnection" , "FAILED TO CLOSE CONNECTION" ,
e.toString() );
} catch ( Exception e ) {
objErrHdl.LogError( this.getClass().getName() , "CloseConnection" , "FAILED TO CLOSE CONNECTION" ,
e.toString() );
}
}
这是我的单元测试:
@Test
public void testCloseConnection() throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
serverSocket = new ServerSocket(6668);
Method method = Systematic.class.getDeclaredMethod("CloseConnection");
method.setAccessible(true);
method.invoke(systematic);
clientSocket = new Socket("127.0.0.1", 6668);
clientSocket.close();
out.close();
}
@Test
public void testCloseConnectionException() throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, IOException {
Method method = Systematic.class.getDeclaredMethod("CloseConnection");
method.setAccessible(true);
method.invoke(systematic);
clientSocket = new Socket("0", 33654);
}
@Test
public void testCloseConnectionIOException() throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
Method method = Systematic.class.getDeclaredMethod("CloseConnection");
method.setAccessible(true);
Socket s = (Socket) method.invoke(systematic);
Mockito.when(s).thenThrow(new IOException());
}
正如我所说,我的单元测试的 testCloseConnectionException 是唯一成功覆盖了我正在测试的 CloseConnection 方法的一部分。谢谢。
【问题讨论】:
-
你能说明如何在包含方法 CloseConnection 的类中设置/创建字段和 clientSocket 吗?在通过反射调用私有方法之前,我也看不到如何从测试中传递该字段的值。
-
变量设置如下:
private Socket clientSocket = null; private OutputStreamWriter out = null; -
我用来覆盖捕获异常部分的代码是这样的:
@Test public void testCloseConnectionThrowsException() { serverSocket = new ServerSocket(6668); Method method = Systematic.class.getDeclaredMethod("CloseConnection"); method.setAccessible(true); method.invoke(systematic); clientSocket = new Socket("127.0.0.1", 6668); clientSocket.close(); out.close();}
标签: java sockets junit mockito ioexception