[英]How to capture parameters of a static void method in JUnit
How do I test that my method calls a static void method with the right parameters?如何测试我的方法是否使用正确的参数调用了静态 void 方法?
public void sendMessages(Collection<Message> messages) {
messages.forEach(message -> {
String type = calculateType(message);
Postman.send(type, message.getText());
});
}
Yes, you need to use PowerMock for that.是的,您需要为此使用 PowerMock。
@RunWith(PowerMockRunner.class)
@PrepareForTest(YourClass.class)
And here instead of type and message.getText() you can use Mockito's ArgumentCaptor
在这里,您可以使用 Mockito 的
ArgumentCaptor
而不是 type 和 message.getText()
Use PowerMock's mockStatic() and verifyStatic() and Mockito's ArgumentCaptor on the static void method like this to prevent the actual static method from being called and to verify that it was called with the right parameters:像这样在静态 void 方法上使用 PowerMock 的 mockStatic() 和 verifyStatic() 以及 Mockito 的 ArgumentCaptor 来防止调用实际的静态方法并验证它是否使用正确的参数调用:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Postman.class)
public class MyTest {
@Test
public void testSendMessages() {
// given
List<Message> messages = Arrays.asList(new Message("text1"), new Message("text2"));
PowerMockito.mockStatic(Postman.class);
// when
instance.sendMessages(messages);
// then
ArgumentCaptor<String> messageTextCaptor = ArgumentCaptor.forClass(String.class);
PowerMockito.verifyStatic(Mockito.times(2));
Postman.send(Matchers.any(), messageTextCaptor.capture());
List<String> capturedMessageTexts = messageTextCaptor.getAllValues();
assertThat(capturedMessageTexts.get(0), CoreMatchers.equalTo("text1"));
assertThat(capturedMessageTexts.get(1), CoreMatchers.equalTo("text2"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.