1

我有一个 Spring Boot 非 Web 应用程序。

我为我的应用程序添加了一些运行良好的集成测试。

我的主类用@SpringBootApplication和 注释,我的集成测试类用@RunWith(SpringRunner.class)和注释@SpringBootTest

如果我将主类注释更改为@Configurationand @ComponentScan and@EnableAutoConfiguration明确,我的测试类会给出一个编译时错误,说它无法检测到正在使用的类之一,并迫使我添加更多信息。

所以我必须更改如下注释@RunWith(SpringRunner.class)@SpringBootTest(classes = EligibilityJobRunner.class).

我读过这@SpringBootApplication是上述三个注释的便利注释,那么为什么会有这种差异?非常感谢。

4

1 回答 1

0

@SpringBootApplication是一个元注释,它应用的注释比您替换它的注释更多:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

如果您不想使用@SpringBootApplication,请尝试使用以下所有注释来注释您的类:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan

在您的情况下,@SpringBootConfiguration缺少。

下次运行测试时,在SpringBootTestContextBootstrapper.java中的各个点放置调试断点以查看幕后情况。

但我认为这些行表明问题出在哪里:

    Class<?> found = new SpringBootConfigurationFinder()
            .findFromClass(mergedConfig.getTestClass());
    Assert.state(found != null,
            "Unable to find a @SpringBootConfiguration, you need to use "
                    + "@ContextConfiguration or @SpringBootTest(classes=...) "
                    + "with your test");
于 2017-05-01T15:36:24.963 回答