문제

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top