【问题标题】:Injecting mock @Service for Spring unit tests为 Spring 单元测试注入模拟 @Service
【发布时间】:2011-01-07 09:26:56
【问题描述】:

我正在测试一个使用 @Autowired 注入服务的类:

public class RuleIdValidator implements ConstraintValidator<ValidRuleId, String> {

    @Autowired
    private RuleStore ruleStore;

    // Some other methods
}

但是如何在测试期间模拟 ruleStore?我不知道如何将我的模拟 RuleStore 注入 Spring 和自动装配系统。

谢谢

【问题讨论】:

    标签: java unit-testing spring spring-mvc mockito


    【解决方案1】:

    Mockito 很容易:

    @RunWith(MockitoJUnitRunner.class)
    public class RuleIdValidatorTest {
        @Mock
        private RuleStore ruleStoreMock;
    
        @InjectMocks
        private RuleIdValidator ruleIdValidator;
    
        @Test
        public void someTest() {
            when(ruleStoreMock.doSomething("arg")).thenReturn("result");
    
            String actual = ruleIdValidator.doSomeThatDelegatesToRuleStore();
    
            assertEquals("result", actual);
        }
    }
    

    在 Mockito javadoc 或 blog post 中阅读有关 @InjectMocks 的更多信息,我前段时间就该主题写过。

    从 Mockito 1.8.3 开始可用,在 1.9.0 中增强。

    【讨论】:

      【解决方案2】:

      您可以使用 Mockito 之类的东西来模拟测试期间返回的规则库。这个 Stackoverflow 帖子有一个很好的例子:

      spring 3 autowiring and junit testing

      【讨论】:

      • 谢谢,我错过了那个。 ReflectionTestUtils.setField(validator, "ruleStore", ruleStore);
      【解决方案3】:

      您可以执行以下操作:

      package com.mycompany;    
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.DependsOn;
      import org.springframework.stereotype.Component;
      
      @Component
      @DependsOn("ruleStore")
      public class RuleIdValidator implements ConstraintValidator<ValidRuleId, String> {
      
          @Autowired
          private RuleStore ruleStore;
      
          // Some other methods
      }
      

      您的 Spring 上下文应如下所示:

      <context:component-scan base-package="com.mycompany" />
      
      <bean id="ruleStore" class="org.easymock.EasyMock" factory-method="createMock">
          <constructor-arg index="0" value="com.mycompany.RuleStore"/>
      </bean>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-02
        • 1970-01-01
        • 2021-05-28
        • 2019-07-04
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多