[英]Unit test for void method
I need to write unit test for some static void
methods with an unknown/unpredictable side effect. 我需要为一些具有未知/不可预测副作用的静态
void
方法编写单元测试。 For example 例如
public void doSth() {
try {
HttpPostUtil.sendRequest("abc", "xyz");
} catch(Exception ex) {
ex.printStackTrace();
}
}
HttpPostUtil
is in another jar file. HttpPostUtil
在另一个jar文件中。 It is out of my control and it will post the data to some web services . 这是我无法控制的,它将把数据发布到某些Web服务。 What is the testing methodology that we could do in this situation?
在这种情况下,我们可以做的测试方法是什么? (
PowerMockito
is not allowed here :() (此处不允许使用
PowerMockito
:()
Because it is void method the only thing you can test is behaviour. 因为它是无效方法,所以您唯一可以测试的就是行为。 In such situation you have few options
在这种情况下,您别无选择
Generally speaking - if it is hard to test -> it is hard to use -> implementation is bad -> so it needs refactoring, not tuning the tests. 一般来说-如果很难测试->很难使用->实现不好->因此需要重构,而不是调整测试。
While testing a method, you should always just test that method and mock the other calls to other methods. 在测试方法时,您应该始终仅测试该方法并模拟对其他方法的其他调用。 Because the other methods should have been tested in their own test methods.
因为其他方法应该已经在自己的测试方法中进行了测试。
Here you simply need 2 tests if you also want to test the catch case. 在这里,如果您还想测试捕获盒,则只需进行2次测试。 With Mockito:
使用Mockito:
@InjectMocks
private YourClass yourClass;
@Mock
private HttpPostUtil httpPostUtil;
@Test
public void testDoSthPositive() {
// Run Test
yourClass.doSth();
// Control
verify(httpPostUtil).sendRequest("abc", "xyz");
verifyNoMoreInteractions(httpPostUtil); // Optional
}
@Test
public void testDoSthNegative() {
// Preparation
NullPointerException exceptionMock = mock(NullPointerException.class);
doThrow(exceptionMock).when(httpPostUtil).sendRequest("abc", "xyz");
// Run Test
yourClass.doSth();
// Control
verify(exceptionMock).printStackTrace();
verifyNoMoreInteractions(exceptionMock, httpPostUtil); // Optional
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.