1

So i have a multi maven module project, with a module for controllers and a module that contains the spring boot start up application class.

myApp - deployment (module) - controllers (module)

In the controllers module i want to be able to test them using mockMvc

however when i run it i get the following error:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

what i want to do is still be able to test this, can i create an test application and use that?

@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
@ActiveProfiles(Constants.TEST)
public class ControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @Test
  public void contextLoads() {
    assertNotNull(mockMvc);
  }

}
user1555190
  • 2,803
  • 8
  • 47
  • 80
  • You can create a dedicated SpringBootApplication just like the normal class have the main function under your module test package – Liping Huang Feb 22 '19 at 12:51

1 Answers1

1

You can create a "test config" class inside your test package like this:

@SpringBootApplication
public class TestConfig {

}

I'm using this a proach for custom repository or services libe that I need to test

than you can annotate your class with

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc

and than you can

@Autowired
protected MockMvc mockMvc;

and all the other stuff you need.

hope this helps

rick
  • 1,869
  • 13
  • 22
  • Thats kinda works, but i still want to be able to use WebMvcTest.. is there anything else other than SpringBootTest i can use instead... to only load controllers. – user1555190 Feb 22 '19 at 13:43
  • 1
    no i meant i want to use WebMvcTest instead of SpringBootTest to start the app up. – user1555190 Feb 22 '19 at 13:54
  • no then I think you can't, is matter of component scan, see https://stackoverflow.com/questions/43515279/error-unable-to-find-springbootconfiguration-when-doing-webmvctest-for-spring – rick Feb 22 '19 at 13:59
  • or directly https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-detecting-config – rick Feb 22 '19 at 14:01
  • yes i can by placing the TestConfig in the same package as the test classes. it then was picked up. :) – user1555190 Feb 22 '19 at 14:03
  • you are right, I don't know why I keep mixing your question with the @SpringBoot Test :D – rick Feb 22 '19 at 14:05