【发布时间】:2021-11-26 05:05:30
【问题描述】:
我想在我的 Junit5 单元测试中将值注入到带有 @Value 注释的私有字段。
@Value("$(invoice.maxRetry)")
private maxRetry;
我参考了this 并使用了 ReflectionTestUtils.setField,它通过注入一个值解决了我的问题,但在验证编号时失败了。方法被调用的次数。
我的班级:
public class MessageProcessor {
@Value("$(invoice.maxRetry)")
private maxRetry;
protected void handleMessage() {
if(retry > maxRetry) {
kafkaTemplate.sendMessage(msg);
}
}
测试类:
@ExtendWith(MockitoExtension.class)
public class MessageProcessorTest {
@Mock
private kafkaTemplate kafkaTemplate;
@Mock
private MessageProcessor messageProcessor
@Test
test() {
ReflectionTestUtils.setField(messageProcessor, "maxRetry", "5");
doNothing().when(kafkaTemplate).sendMessage(any());
messageProcessor.handleMessage();
verify(kafkaTemplate).sendMessage(any());
}
}
在测试上面运行时出错
org.mockito.exceptions.verification.TooManyActualInvocations:
kafkaTemplate.sendMessage(<any>);
Wanted 1 time:
But was 2
我希望 kafkaTemplate.sendMessage(); 只被调用一次,但在添加 ReflectionTestUtils 后被调用两次。
需要有关如何解决此问题的建议。
【问题讨论】:
标签: spring-boot reflection mockito junit5 spring-boot-test