简体   繁体   中英

Injecting mock @Service for Spring unit tests

I am testing a class that uses use @Autowired to inject a service:

public class RuleIdValidator implements ConstraintValidator<ValidRuleId, String> {

    @Autowired
    private RuleStore ruleStore;

    // Some other methods
}

But how can I mock ruleStore during testing? I can't figure out how to inject my mock RuleStore into Spring and into the Auto-wiring system.

Thanks

It is quite easy with 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.

Available as of Mockito 1.8.3, enhanced in 1.9.0.

You can use something like Mockito to mock the rulestore returned during testing. This Stackoverflow post has a good example of doing this:

spring 3 autowiring and junit testing

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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