这是我的Spring Controller测试用例
@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class)
public class MyControllerTest {
@MockBean
private MyService myService;
}
所以这是一个专门针对MyController中方法的单元测试。但是当我运行测试时,Spring似乎开始实例化OtherController及其所有依赖项。
我已尝试将上述内容更新为
@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class, excludeFilters = @ComponentScan.Filter(value= OtherController.class, type = FilterType.ANNOTATION))
public class MyControllerTest {
...
}
但是春天似乎仍在接线。这是Spring抛出的错误,因为它在我专门运行上面的测试时试图实例化OtherController。
2017-01-06 12:09:46.207 WARN 18092 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'otherController' defined in file [C:\..OtherController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOtherService' defined in com.my.myApplication: Unsatisfied dependency expressed through method 'getOtherService' parameter 0org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOtherService' defined in com.myOrg.MyServiceApplication: Unsatisfied dependency expressed through method 'getPositionService' parameter 0
导致这种情况的原因是什么?
答案 0 :(得分:0)
您有可能通过@Componentscan
或类似的方式意外触发bean扫描。
例如,正如this answer中所解释的那样,Spring可能正在检测您的生产" @SpringBootApplication
Application
类,包含所带来的所有组件扫描。如果是这样,请确保"覆盖"你的生产"使用" test"的应用程序类一个推杆......
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
...在一个覆盖"生产"的位置。应用
例如,如果您的IDE没有被类名冲突搞砸:
"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
作为替代方案,我也发现在我的情况下这也可以(即将应用程序放在测试控制器文件夹中)
"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