Injecting mock @Service for Spring unit tests
-
30-09-2019 - |
Question
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
Solution
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.
OTHER TIPS
You can use something like Mockito to mock the rulestore returned during testing. This Stackoverflow post has a good example of doing this:
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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow