Scenario

Sample project here

An abstract test with @ExtendWith(SpringExtension.class) that loads a web application.

Two tests extend it. One of them has a field with @SpyBean.

What happens

When starting the second test, the spring context is restarted.

Moreover, the previous context apparently is not shutdown, as the second test fails with java.net.BindException: Address already in use: bind.

If the @SpyBean is removed, it works as expected.

What is expected

All tests should share the same context.

Same happens with @MockBean, whether a bean is already in the context or not.

How to run

Run the tests in your IDE or with mvn test.

Comment From: wilkinsona

Thanks for the detailed report and sample. The behavior you have seen is expected. When you spy on a bean it changes it. This change to the bean means that it cannot be shared with a test that has not spied on the bean. To ensure that one test gets the spied bean and one gets the normal bean, two application contexts are used.

You can avoid the port clash either by using a mock web environment or using a random port. You could also disable caching of the context (@DirtiesContext is one way to do this).

Comment From: davidzhangmo

Restarting a new context is not a problem, however, the previous context should be shutdown.

Comment From: spyro2000

@davidzhangmo Yes, that's the real problem, because an embedded server gets not shutdown and blocks the port.

Comment From: wilkinsona

@spyro2000 That has already been addressed in an earlier comment.