hamvocke / spring-testing

A Spring Boot application with lots of test examples
https://www.martinfowler.com/articles/practical-test-pyramid.html
1.11k stars 439 forks source link

JUnit Errors - You cannot use argument matchers outside of verification or stubbing - NullPointerException #19

Closed jx-pt closed 2 years ago

jx-pt commented 2 years ago

Not sure why, but six of the tests fail.

org.mockito.exceptions.misusing.InvalidUseOfMatchersException

Exemple, misplaced or misused argument matcher detected here: -> at example.ExampleControllerTest.shouldTellIfPersonIsUnknown(ExampleControllerTest.java:56)"

This method

  @Test
    public void shouldTellIfPersonIsUnknown() throws Exception {
        given(personRepository.findByLastName(anyString())).willReturn(Optional.empty());

        var greeting = subject.hello("Pan");

        assertThat(greeting, is("Who is this 'Pan' you're talking about?"));
    }
hamvocke commented 2 years ago

Thanks for making me aware of this. Digging into this issue I realised that I messed up royally during the most recent version upgrade. I migrated the build pipeline from Travis to CircleCI during the latest round of upgrades and didn't notice that the gradle test step didn't find any tests at all, leaving me completely in the dark about test failures.

Back to your issue: This was caused by a lack of initializing Mockito properly. A simple MockitoAnnotations.openMocks(this) solves that issue. This is fixed in the latest master.

I added a few other updates while I was at it. All tests are now running on jUnit 5 properly. Previously I had still two jUnit versions due to pact pulling in jUnit 4 which was the root of all these issues we saw.

Thanks again for reporting, I went down a deep rabbit hole and fixed a whole lot of things I messed up. Everything should be back to normal now.