且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在使用Spring Boot @WebMvcTest进行测试时,如何从我的上下文中排除其他@Controller

更新时间:2023-09-05 12:39:52

请确保您的测试选择 Application.class ,不包含 @ComponentScan 注释。例如,这是您的包结构

Please make sure the Application.class your test picks up, doesn't contain @ComponentScan annotation. For example, this is your package structure

abc-project
  +--pom.xml
  +--src
    +-- main
      +-- com
        +-- abc
          +-- Application.java
          +-- controller
            +-- MyController.java
    +-- test
      +-- com
        +-- abc
          +-- Application.java
          +-- controller
            +-- MyControllerTest.java

Application.java > test 应该与此示例类似,

The Application.java under test should look similar to this example,

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