我正在使用 Spring Boot 创建一个微服务,一切都很好,除了一些小烦恼。
在我的测试类中 Autowiring ,我在 @Autowired 注释上收到以下警告:
Autowired members must be defined in the valid spring bean(@Component/@Service,etc.) Checks that auto wired members are defined in valid Spring bean (@Component|@Service|...).
这是使用以下测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class MyRecordTest {
public static final String NUMBER = "ABC/123456";
@Autowired
private MyFactory factory;
@Autowired
private Marshaller marshaller;
...
}
我的应用程序配置类定义为
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Marshaller getMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("com.my.classes");
return marshaller;
}
}
并且 MyFactory 有 @Component 注解:
@Component
public class MyFactory {
...
}
我该如何解决这个问题?
此外,我的应用程序中唯一未覆盖的行是 public static void main 方法中的 SpringApplication.run 行:
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
我怎样才能得到这个覆盖或忽略?
最佳答案
正如 Anand 所说,您需要在测试中执行以下操作,以便在测试中 Autowiring 依赖项:
@RunWith(SpringRunner.class)
@SpringBootTest
像这样:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyRecordTest {
public static final String NUMBER = "ABC/123456";
@Autowired
private MyFactory factory;
@Autowired
private Marshaller marshaller;
...
}
关于unit-testing - IntelliJ 中 Spring Boot 的 Bean 扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32821839/