[英]JUnit not Initializing Services Parameters
我有一個 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 應用程序,並且在 application.properties 文件中找到的參數將簡單地可供 MyService 服務使用,就像我運行應用程序本身(而不是 junit)時一樣。
顯然我做錯了什么,應用程序上下文不可用我設置這個 junit 的方式。 對於使它正常工作的任何想法,我將不勝感激。
謝謝!
在 Junit 測試中連接被測 class,就像在任何生產代碼 class 中一樣。
@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();
}
}
如果你願意,你可以在測試 class 中添加參數@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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.