所以,我想用 testcontainers 來測驗 elasticsearch。測驗容器運行良好并且開始良好,但是當我想從我的服務呼叫一個方法時,這是 null,因為沒有注入,我不知道為什么。
@Testcontainers
@SpringBootTest
@ActiveProfiles("dev")
public class ArticleServiceTestDemo {
@Autowired
private ArticleService articleService;
private static final String ELASTICSEARCH_VERSION = "7.9.2";
private static final DockerImageName ELASTICSEARCH_IMAGE = DockerImageName
.parse("docker.elastic.co/elasticsearch/elasticsearch")
.withTag(ELASTICSEARCH_VERSION);
@Test
public void myTest() {
try (
ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE);
) {
container.start();
ResponseEntity<Article> article = articleService.persistArticle(new ArticleRequestDto());
assertTrue(article.getStatusCode().is2xxSuccessful());
}
}
}
這是我的錯誤:
java.lang.NullPointerException: Cannot invoke "com.ArticleService.persistArticle(com.ArticleRequestDto)" because "this.articleService" is null
當我運行一個簡單的 SpringBootTest(沒有彈性搜索連接和測驗容器)ArticleService時,注入良好。但是在測驗容器的測驗中,這沒有注入。
uj5u.com熱心網友回復:
請檢查 ArticleService 類是否為 Spring bean,表示 ArticleService 類是否被 @Service 或 @Component 注解。當您在一個類上應用@Component 時,Spring bean 容器會在 Spring Bean 容器中初始化為 bean 物件,并且 Spring Container 會嘗試將初始化的 bean 物件注入注解的 @Autowired 欄位。如果您在類 NullPointerException 上應用 @Component,則會發生。
uj5u.com熱心網友回復:
例如這個測驗運行良好。ArticleService并被注入。
@SpringBootTest
public class DemoTest {
@Autowired
private ArticleService articleService;
@Test
public void simpleTest() {
articleService.persistArticle(new ArticleRequestDto());
}
}
uj5u.com熱心網友回復:
你能檢查一下@ActiveProfiles("dev")是不是弄亂了bean的接線嗎?您運行正常的示例沒有它。例如洗掉它并驗證測驗是否運行?
另一方面,如果您通過呼叫來自己管理測驗容器的生命周期:container.start();那么您不需要@Testcontainers來自Testcontainers 的 JUnit 擴展的注釋,它查看標記為的靜態/實體欄位@Container并創建和啟動/停止這些自動地。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485196.html
上一篇:ElasticsearchStats和SumAggregation底層
下一篇:在日期之間具有當前日期的提升結果
