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
1 Answer. Show activity on this post. var service = new MockLoginService(); beforeEachProviders(() => [ provide(TestService, { useValue: service })]); it('should load languages', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { tcb . createAsync(LoginComponent).
This is easily done by using Spring Boot's @MockBean annotation. The Spring Boot test support will then automatically create a Mockito mock of type SendMoneyUseCase and add it to the application context so that our controller can use it.
If you want to create just a Mockito test you could use the annotation @RunWith(MockitoJUnitRunner. class) instead of @SpringBootTest . But if you want to create a Spring Boot integration test then you should use @MockBean instead of @Mock and @Autowired instead of @InjectMocks .
A mock doesn't have any real implementation. @InjectMocks would try to find and call setters for whatever mock objects have already been created and pass them in.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With