4

Using @WebMvcTest will auto-configure all web layer beans by looking for a @SpringBootConfiguration class (such as @SpringBootApplication).

If the configuration class is in a different package and can't be found by scanning, can I provide it directly to @WebMvcTest?

NatFar
  • 2,090
  • 1
  • 12
  • 29

2 Answers2

4

The following will point to the correct @SpringBootApplication class:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = {MyController.class})
@ContextConfiguration(classes={MySpringBootApplicationClass.class})
public class MyControllerTest {
    //...
}
NatFar
  • 2,090
  • 1
  • 12
  • 29
4

If you are using @WebMvcTest for your test , it means you are focusing mainly on testing the spring mvc layer and not going any deeper into the application.

So this annotation can be used only when a test focuses on Spring MVC components. By default, tests annotated with @WebMvcTest will also auto-configure Spring Security and MockMvc (include support for HtmlUnit WebClient and Selenium WebDriver). For more fine-grained control of MockMVC the @AutoConfigureMockMvc annotation can be used.Typically @WebMvcTest is used in combination with @MockBean or @Import to create any collaborators required by your @Controller beans.

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {

}

You can then import this configuration class using @import in the @WebMvcTest annotated test class and the beans should be picked up by spring.

Reference : https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39