且构网

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

控制器的 Spring Boot 测试 @WebMvcTest 似乎在上下文中加载其他控制器

更新时间:2023-02-25 16:23:45

可能是您通过 @Componentscan 或类似方法意外触发了 bean 扫描.

Chances are that you are triggering the bean scanning by accident via a @Componentscan or the likes.

例如,如 这个答案,Spring 可能正在检测您的生产"@SpringBootApplication Application 类,以及它带来的所有组件扫描.如果是这样,请确保您用测试"一个推杆覆盖"您的生产"应用程序类......

For instance, as explained in this answer, Spring may be detecting your "production" @SpringBootApplication Application class, with all the component scans it brings about. If so make sure you "overwrite" your "production" Application class with your "test" one putting...

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

...在会覆盖生产"应用程序的位置.

...in a location that would override the "Production" Application.

例如,如果您的 IDE 没有被类名冲突弄乱:

For instance, if your IDE doesn't get messed by class name ***es:

"production" -> src/main/java/com/mycompany/Application.java
             -> src/main/java/com/mycompany/controllers/MyController.java
"test"       -> src/test/java/com/mycompany/Application.java
             -> src/test/java/com/mycompany/controllers/MyControllerTest.java

作为替代,我还发现在我的情况下这也有效(即将应用程序放在测试控制器文件夹中)

As an alternative I also have found that in my case this works as well (i.e. placing the Application in the test controllers folder)

"production" -> src/main/java/com/mycompany/Application.java
             -> src/main/java/com/mycompany/controllers/MyController.java
"test"       -> src/test/java/com/mycompany/controllers/Application.java
             -> src/test/java/com/mycompany/controllers/MyControllerTest.java