4

I have multiple @WebMvcTest-annotated test classes that run successfully if executed separately (e.g. via mvn -Dtest=BTest test or via IDE).

However if they'are executed together (e.g. via mvn test or mvn package) one test fails (BTest in the below code) because @SpyBean-annotated field doesn't intercept method calls. The other tests don't have any @SpyBean's.

The corresponding code structure is below:

// ATest.java
@WebMvcTest
class ATest {
   ...
}

// BTest.java
@WebMvcTest
class BTest {

    ...

    @SpyBean
    private ComponentToSpyOn comp;

    ...

    @Test
    void testSomething() {

        ...

        latch = new CountDownLatch(1);

        Mockito.doAnswer(inv -> {
            var result = inv.callRealMethod();
            latch.countDown();
            return result;
        }).when(comp).execute(any());
            
        // Execute something that would lead to call interception

        // Wait for method return
        if (!latch.await(3000, TimeUnit.MILLISECONDS)) {
            latch = null;
            throw new TimeoutException();
        }

       ...

    }
}

// CTest.java
@WebMvcTest
class CTest {
   ...
}

I've tried to apply @DirtiesContext on the affected test class and its methods according to the recommendation here @SpyBean with few Integration tests doesn't work correctly but with no result.

As the @SpyBean isn't null and doesn't intercept method call it must be initialized somehow incorrectly.

I've solved the problem with Maven configuration as described here https://stackoverflow.com/a/68619944/971355 Each test on a separate VM but I don't like the solution as it slows down the test execution for sure.

ka3ak
  • 2,435
  • 2
  • 30
  • 57

0 Answers0