为Spring单元测试注入模拟@Service

时间:2011-01-07 09:26:57

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

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

public class RuleIdValidator implements ConstraintValidator<ValidRuleId, String> {

    @Autowired
    private RuleStore ruleStore;

    // Some other methods
}

但是如何在测试期间模拟ruleStore?我无法弄清楚如何将我的模拟RuleStore注入Spring并进入自动布线系统。

由于

3 个答案:

答案 0 :(得分:15)

使用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中的@InjectMocks或我前一段时间撰写的有关该主题的blog post

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

答案 1 :(得分:10)

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

spring 3 autowiring and junit testing

答案 2 :(得分:2)

您可以执行以下操作:

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应该是这样的:

<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>