Spring 无法在控制器构造函数中模拟注入的依赖项
我在模拟被注入控制器的对象时遇到问题 我正在运行一个集成测试。在我的测试中,我有以下设置:Spring 无法在控制器构造函数中模拟注入的依赖项,spring,unit-testing,spring-boot,dependency-injection,Spring,Unit Testing,Spring Boot,Dependency Injection,我在模拟被注入控制器的对象时遇到问题 我正在运行一个集成测试。在我的测试中,我有以下设置: @RunWith(SpringRunner.class) @SpringBootTest public class AuthenticationTests { @TestConfiguration public class Config { @Bean @Primary public AbstractClient client() { return new Abs
@RunWith(SpringRunner.class)
@SpringBootTest
public class AuthenticationTests {
@TestConfiguration
public class Config {
@Bean
@Primary
public AbstractClient client() {
return new AbstractClient() {
@Override
public ManagedChannel getChannel() {
return new ManagedChannel();
}
};
}
}
}
在被测试的控制器中,AbstractClient
被注入依赖项,如下所示:
@Controller
public class MyController {
private ManagedChannel managedChannel;
public MyController(AbstractClient client) {
managedChannel = client.getChannel();
}
}
每当我运行测试时,@TestConfiguration类中定义的AbstractClient永远不会被注入,而默认的是(注释为@Service)
有人能帮忙吗?您的配置需要是一个
公共静态
类。不幸的是,更改为公共静态并没有什么区别MyController
bean在您的测试中是如何实例化的?您的测试代码在哪里?我的理解是,通过注释@SpringBootTest,整个spring boot应用程序都被实例化了——这也将实例化MyController(及其关联的路由)?另外-我使用@SpringBootTest的原因是实际测试WebSecurity配置适配器中的一些身份验证代码-这似乎是唯一的方法。其他测试是控制器的普通单元测试。