unit-testing - IntelliJ 中 Spring Boot 的 Bean 扫描

标签 unit-testing annotations spring-boot autowired

我正在使用 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/

相关文章:

c++ - CppUnit,非常简单的测试代码崩溃了,为什么?

javascript - 如何使用 enzyme 对React中的选择元素是否具有焦点进行单元测试?

android - 如何使用协程测试加载指示器(TestCoroutineScope 已弃用)?

xml - 在 Spring 3 中使用注解注册转换器和 converterFactories

java - spring security 在重定向到 logout.jsp 时给出错误

scala - 我们是否需要测试因异常而失败的公共(public)方法的失败场景?

java - 如何在 Spring-WS 中定义基于模式的端点

java - Java 注解会影响运行时性能吗?

java - 使用SQL查询创建索引和在JPA中使用@Index创建索引的区别

java - Hibernate 对父类的查询会创建无效的联合查询