简体   繁体   English

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

[英]Injecting mock @Service for Spring unit tests

I am testing a class that uses use @Autowired to inject a service: 我正在测试一个使用@Autowired注入服务的类:

public class RuleIdValidator implements ConstraintValidator<ValidRuleId, String> {

    @Autowired
    private RuleStore ruleStore;

    // Some other methods
}

But how can I mock ruleStore during testing? 但是如何在测试期间模拟ruleStore? I can't figure out how to inject my mock RuleStore into Spring and into the Auto-wiring system. 我无法弄清楚如何将我的模拟RuleStore注入Spring并进入自动布线系统。

Thanks 谢谢

It is quite easy with Mockito : 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);
    }
}

Read more about @InjectMocks in the Mockito javadoc or in a blog post that I wrote about the topic some time ago. 了解更多关于@InjectMocks中的javadoc的Mockito或在博客中 ,我前段时间写的话题。

Available as of Mockito 1.8.3, enhanced in 1.9.0. 自Mockito 1.8.3起可用,增强型1.9.0。

You can use something like Mockito to mock the rulestore returned during testing. 您可以使用Mockito之类的东西来模拟测试期间返回的规则库。 This Stackoverflow post has a good example of doing this: 这篇Stackoverflow帖子有一个很好的例子:

spring 3 autowiring and junit testing 春季3自动装配和junit测试

You can do following: 你可以这样做:

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
}

And your Spring Context should looks like: 你的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM