Fabien Thouraud
Fabien Thouraud

Reputation: 909

Mockito injects mocks twice with JUnit 5

I started testing Spring Boot 2.0.0 and I encountered a strange behaviour with Mockito 2.17.0 and JUnit 5.1.0.

From what I saw, the way to get the mocks injected into the desired bean is to use the new @ExtendWith annotation with the MockitoExtension class.

So, here's my test class:

@ExtendWith(MockitoExtension.class)
class MyServiceTest {

    @Mock
    private A a;

    @Mock
    private B b;

    @InjectMocks
    private MyService myService;

    // The test methods are omitted
}

That seemed fine but I found that the mocks didn't get called as expected and I figured out that this was due to a different instance of a and b inside the test class and the service itself.

Actually, it's because of the MockitoExtension being applied twice and the second time it is applied, the myService field isn't evaluated to null (obviously) which imply that the newly created mocks (a and b) aren't set to the current myService instance or a new one either.

Am I forgetting something?

I assume I could handle the mocks myself but I think that it isn't the purpose of the InjectMocks annotation.

Thank you for your time.

Upvotes: 1

Views: 1095

Answers (1)

VaL
VaL

Reputation: 1167

It looks like you hit Mockito issue: mockito#1346.

It's already fixed, so you may wait for a public release or use dev build 2.17.2: https://bintray.com/mockito/maven/mockito-development/2.17.2 (release notes)

Upvotes: 4

Related Questions