JUnit未初始化服务参数



我有一个SpringBoot应用程序,基本结构类似于以下内容:

应用程序:

@SpringBootApplication
public class MyApplication {
@Autowired
MainService mainService;
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}

@KafkaListener(topics = "myTopic")
public void listen(String message) {
this.graphicService.performWork();
}
}

第一服务:

@Service
public MainService {
@Autowired MyService myService;
public performWork() {
this.myService.doStuff();
}
}
第二服务:

@Service
public class MyService {
// server.param1 and server.param2 are defined in application.properties file
@Value("${server.param1}")
private String param1;
@Value("${server.param2}")
private String param2;
@PostConstruct
public void initService(){
}
public void doStuff() {
// do stuff assuming the parameters param1 and param 2 of this autowired service have already been initialized
}
}

我有一个像下面这样的junit:

@SpringBootTest(classes = MyApplication.class)
class MyServiceTest {
@Test
void testMyService() {
MyService myService = new MyService();
myService.doStuff();
}
}

当我执行testMyService时,我得到一个抛出的异常,基本上是这样的:

java.lang.IllegalStateException: Failed to load ApplicationContext
.
.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myApplication': Unsatisfied dependency expressed through field 'mainService';
.
.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainService': Unsatisfied dependency expressed through field 'myService'
.
.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed
.
.
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'server.param1' in value "${server.param1}"

应用程序在操作上运行良好。我认为通过设置junit的方式,springboot应用程序会简单地启动,并在应用程序中找到参数。当我运行应用程序本身(而不是junit)时,属性文件将简单地对MyService服务可用。

显然我做错了什么,应用程序上下文是不可用的方式,我有这个junit设置。我将非常感谢任何让它正常工作的想法。

谢谢!

在Junit测试中连接被测类,就像在任何生产代码类中一样。

@SpringBootTest将自动检测@SpringBootApplication,因此不需要额外的参数。只需像在应用程序类中那样连接所需的依赖项。

如果存在,测试将使用src/test/resources/application.properties(或yml)文件。如果不存在,则使用src/main/resources/application.properties。因此,如果您在生产application.yml中使用环境变量,则将此文件复制到测试资源中,并使用测试的虚拟参数填充参数。

@SpringBootTest
class MyServiceTest {
@Autowired MyService myService;
@Test
void testMyService() {
myService.doStuff();
}
}

如果您愿意,您可以在测试类中添加@TestPropertySource(properties参数

@SpringBootTest
@TestPropertySource(properties = {
"server.param1=srv1",
"server.param2=srv2"
})
class MyServiceTest {
...

确保你的依赖项中有spring-boot-starter-test

Maven的例子:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.7.5</version>
<scope>test</scope>
</dependency>

最新更新