I need to write unit test for some static void
methods with an unknown/unpredictable side effect. For example
public void doSth() {
try {
HttpPostUtil.sendRequest("abc", "xyz");
} catch(Exception ex) {
ex.printStackTrace();
}
}
HttpPostUtil
is in another jar file. It is out of my control and it will post the data to some web services . What is the testing methodology that we could do in this situation? ( PowerMockito
is not allowed here :()
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. With 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.