Issue
I found that the process on running integration test, it began two different spring context(@See GenericWebApplicationContext
):
- The class which are annotated with
@AutoConfigureMockMvc
using the same spring context. - Other class which are none annotated with
@AutoConfigureMockMvc
(like mapper test) using the other one.
It made my integration test failed as it bootstraped spring context twice, because my project would did initialization when spring context bootstrap.
Why would it happened?
When I annotated all
the test class with @AutoConfigureMockMvc
, integration test ran well. Obviously service and dao layer needn't to use this annotation, any way to figure out this problem?
Environment and code
- JDK 8
- SpringBoot Test 5.2.4
- JUnit Jupiter 5.5.2
Lately I am doing unit test by Junit 5, at first tests were only for controller layer and everything looks well when I run integration test began from source code root package,
Those ControllerTest class like:
@Slf4j
@Transactional
@SpringBootTest
@AutoConfigureMockMvc
class DemoControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testCaseHere() throws Exception {
// do mockMvc request test
}
}
but one day an odd issue happened when I did integration test
because I ran a test class by none annotated with @AutoConfigureMockMvc
Test class like( My project dao layer used MyBatis for its orm framework. ):
@Slf4j
@SpringBootTest
@Transactional
class DemoMapperTest {
@Autowired
private DemoMapper demoMapper;
@Test
void demoMapperSelect() {
demo.selectById(9L);
}
}
Junit ran integration testing serially, order is:
- ControllerATest
- MapperATest
- ControllerBTest
- ControllerCTest
- ...
Fitst spring contest initialization happened in ControllerATest ran, second spring contest initialization happened in MapperATest ran.
Comment From: wilkinsona
This is working as designed. Spring Framework's testing support will cache the application context and share it between test classes when the tests' configuration would produce two contexts with identical sets of beans. @AutoConfigureMockMvc
adds some MockMvc-related beans to the application context. In this case, this means that your mapper tests do not have those MockMvc-related beans so a new application context is created for those tests.
It made my integration test failed as it bootstraped spring context twice,
Starting multiple contexts is quite common and shouldn't cause tests to fail. You haven't said what the failure was so I can't offer any guidance on how to address the failure. If you would like to follow up on this, please do so on Stack Overflow or Gitter. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.