2

I updated my project with the latest revision of Spring (2.0.0.RELEASE) and while my tests worked in 2.0.0.RC1, now it doesn't work and it keeps giving me this error :

org.mockito.exceptions.base.MockitoException: Cannot instantiate @InjectMocks field named 'service'! Cause: the type 'PersonService' is an interface. You haven't provided the instance at field declaration so I tried to construct the instance. Examples of correct usage of @InjectMocks: @InjectMocks Service service = new Service(); @InjectMocks Service service; //and... don't forget about some @Mocks for injection :) 

Here I made a minimal project where you can change the version in the pom file to see it succeed on 2.0.0.RC1 and fail in 2.0.0.RELEASE.

For the a full minimal test - please turn to gituhub.

4
  • Do you want to use Mockito and mocked stuff in your test, or do you want to have Spring inject the PersonService bean into your test class? As of now you have both, which doesn't make sense. Commented Mar 2, 2018 at 1:01
  • I want to use Mockito and mocked stuff in my tests atm. Commented Mar 2, 2018 at 1:05
  • Then you can remote the Autowired and SpringBootTest annotations. Commented Mar 2, 2018 at 1:23
  • Upvote for providing the "Minimal Test Reproduction". Commented Mar 2, 2018 at 8:25

1 Answer 1

1

From the documentation for the @InjectMocks

Mockito cannot instantiate inner classes, local classes, abstract classes and of course interfaces.

In your case you should use inside your test:

@InjectMocks private PersonServiceImpl underTest; 

I have checked in your sample from github, if you change to the implementation of service - tests will be passed

Sign up to request clarification or add additional context in comments.

1 Comment

The usual word of warning, along with my upvote of going through actually verifying the example input: the big downside of this annotation is that it fails silently. If it can't inject mocks, it just does nothing. Which can be a real pain to figure. Thus I tend to avoid using it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.