20

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

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Steve
  • 2,207
  • 6
  • 24
  • 35

3 Answers3

20

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.

Bampfer
  • 2,120
  • 16
  • 25
matsev
  • 32,104
  • 16
  • 121
  • 156
10

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

Community
  • 1
  • 1
Jonathan Holloway
  • 62,090
  • 32
  • 125
  • 150
  • Thanks, I missed that one. ReflectionTestUtils.setField(validator, "ruleStore", ruleStore); – Steve Jan 07 '11 at 09:46
2

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>
mokshino
  • 1,435
  • 16
  • 11