0

我通过如下代码创建 Spring ApplicationContext:

public static AnnotationConfigWebApplicationContext startContext(String activeProfile,
                              PropertySource<?> propertySource, Class<?>... configs) {
    AnnotationConfigWebApplicationContext result = new AnnotationConfigWebApplicationContext();
    if (propertySource != null) {
        result.getEnvironment().getPropertySources().addLast(propertySource);
    }
    if (activeProfile != null) {
        result.getEnvironment().setActiveProfiles(activeProfile);
    }
    result.register(configs);
    result.refresh();
    return result;
}

在测试类中,我这样称呼它:

@RunWith(SpringJUnit4ClassRunner.class)
class FunctionalTest {
    private ApplicationContext appContext;

    @BeforeEach
    void init() {
        appContext = Utils.startContext("functionalTest", getPropertySource(), 
                            BaseConfig.class, MyApplication.class, StorageTestConfig.class);
    }
}

它工作正常,没有问题。

现在我正在尝试做同样的事情,但通过注释:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {BaseConfig.class, MyApplication.class, StorageTestConfig.class}, 
                      loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("functionalTest")
@PropertySource(value = "classpath:test-context.properties")
class FunctionalTest {
      @Autowired
      private ApplicationContext applicationContext;
      ...
}

这根本行不通。 applicationContext不是自动装配的,配置中的bean也是如此。你能说我可能做错了吗?

为什么我想从代码切换到注释:我希望能够从配置中自动装配 bean。现在(以上下文创建的代码方式)我应该appContext.getBean("jdbcTemplate", JdbcTemplate.class)在测试方法中编写类似的东西。如果我能写就太好了

@Autowired
private JdbcTemplate jdbcTemplate;

这将起作用:)

4

1 回答 1

1

似乎您同时使用了两个版本的 JUnit:JUnit 4 和 JUnit 5。(或同时使用 JUnit4 api 和 JUnit5 api)

你的注释@Test来自哪里FunctionalTest

org.junit.Test吗?或者是org.junit.jupiter.api.Test吗?

好像是从org.junit.jupiter.api.Test

那么你应该使用@ExtendWith(SpringExtension.class而不是 @RunWith(SpringJUnit4ClassRunner.class)

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {BaseConfig.class, Utils.ServConfig.class, Utils.MvcConfig.class, MyApplication.class, StorageTestConfig.class}, 
                  loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("functionalTest")
@PropertySource(value = "classpath:test-context.properties")
class FunctionalTest {
      @Autowired
      private ApplicationContext applicationContext;

}

请注意,SpringExtension5.0版本以来可用。如果您使用的是较低版本,则必须使用 JUnit4,将测试方法标记为org.junit.Test

在测试类中,我这样称呼它:它工作正常,没有问题。

@RunWith(SpringJUnit4ClassRunner.class)在这里一文不值。您使用 JUnit5 运行此测试。@RunWith不考虑。而是@BeforeEach考虑。因此它正在工作。

在您FunctionalTest没有考虑注释中,因此它不起作用。使用 JUnit4 ( @org.junit.Test, @RunWith) 或 JUnit5 ( @org.junit.jupiter.api.Test, @ExtendWith)。

似乎您同时使用了两个版本的 JUnit:JUnit 4 和 JUnit 5。

如果您不从 JUnit4 迁移到 JUnit 5,请考虑仅使用一个版本的 JUnit。

于 2018-09-09T11:11:56.240 回答