How to test Maven module project with Spring Boot

Stefan picture Stefan · Jun 3, 2016 · Viewed 12k times · Source

I have split a project, based on Spring Boot, into several Maven modules. Now only the war-project contains a starter class (having a main method, starting Spring), the other modules are of type jar.

How do I test the jar projects, if they don't include a starter?

Example JUnit test case header:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(StarterClassInDifferentProject.class)
...

Answer

Gadi picture Gadi · Sep 27, 2016

I think context tests should be available per module so you can find issues with wire and configuration early on and not depend on your full application tests to find them.

I worked around this issue with a test application class in the same module. Make sure this main class is in your test dir.

@SpringBootApplication
public class TestApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

your context should work now.

@RunWith(SpringRunner.class)
@ActiveProfiles(profiles = {Profiles.WEB_REST})
@WebMvcTest(EntityController.class)
@DirtiesContext
public class ServicesControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private Controller controller;

    @Test
    public void testAll() throws Exception {
        given(controller.process(null)).willReturn(null);

        mvc.perform(get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
}