【问题标题】:Springboot & Mockito - Using ReflectionTestUtils.setField calling method twiceSpring Boot 和 Mockito - 使用 ReflectionTestUtils.setField 调用方法两次
【发布时间】: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


    【解决方案1】:

    您可以通过稍微重构您的类并支持构造注入来避免使用ReflectionTestUtils

    public class MessageProcessor {
         
        private String maxRetry;
        private KafkaTemplate template;
    
        // ... any further fields
    
        public class MessageProcessor(@Value("$(invoice.maxRetry)") String maxRetry, KafkaTemplate kafkaTemplate) {
           this.maxRetry = maxRetry;
           this.kafkaTemplate = kafkaTemplate;
        }
    
     }
    

    在您的测试中,您可以通过手动创建被测类的实例 (MessageProcessor) 来控制 maxRetry 的值。

    @ExtendWith(MockitoExtension.class)
    public MessageProcessorTest {
    
      @Mock 
      private KafkaTemplate kafkaTemplate;
    
      private MessageProcessor messageProcessor;
    
      @BeforeEach
      void setUp() {
        this.messageProcessor = new MessageProcessor("42", kafkaTemplate);
    
      }
    
    }
    

    ...然后只依赖 JUnit 和 Mocktio 可以帮助您添加验证。

    【讨论】:

      猜你喜欢
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 2013-12-31
      • 2016-09-29
      • 2021-05-12
      • 2018-12-23
      相关资源
      最近更新 更多