JUnit 5中使用@ContextConfiguration创建测试时无法创建bean

6

我正在尝试为我的应用编写JUnit测试用例。在使用JUnit 5之后,我无法通过@ContextConfiguration创建必要的bean。

它没有抛出任何错误。但是,在测试类中进行自动装配时,我得到了空值。

我添加了以下依赖项:

testImplementation "org.junit.jupiter:junit-jupiter-api:5.3.0"
testCompile('org.junit.jupiter:junit-jupiter-params:5.3.0')
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.3.0"

以及我的代码

@ContextConfiguration(classes = ServiceTestContextConfiguration.class)
public class ApplicationConfigTest {

@Autowired
private ApplicationServiceConfiguration 

应用程序服务配置;

@ContextConfiguration
public class ServiceTestContextConfiguration {
@Bean
public ApplicationServiceConfiguration applicationServiceConfiguration() {
    return new ApplicationServiceConfiguration();
}

我正在使用 Spring Boot 2。


将您的 ServiceTestContextConfiguration 类标记为 @Configuration,然后检查。 - IMParasharG
我尝试使用@Configuration,但它也不起作用。 - abin peter
1个回答

8

可能我们混淆了junit4和junit5的导入。让我们使用@Configuration (org.springframework.context.annotation.Configuration;)对配置类进行注解。

在主要的单元测试中,让我们使用以下内容:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ServiceTestContextConfiguration.class)

使用@BeforeEach代替@Before,确保所有导入都来自junit5(包括断言)

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

非常有用的一个。 - abin peter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接