Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 961
Steve Avatar asked Jan 07 '11 09:01

Steve


People also ask

How do you mock a service to inject in a unit test?

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

How do I mock a service in spring boot?

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.

How do you inject a mock in SpringBootTest?

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 .

Can we use mock and InjectMocks together?

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.


1 Answers

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.

like image 198
matsev Avatar answered Sep 17 '22 16:09

matsev