So, I want to test elasticsearch with testcontainers. Test containers work well and start good, but when I want to invoke a method from my service this is null, because is not injected, and I don't why.
@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());
}
}
}
This is my error:
java.lang.NullPointerException: Cannot invoke "com.ArticleService.persistArticle(com.ArticleRequestDto)" because "this.articleService" is null
When I run a simpe SpringBootTest (without elasticsearch connection and testcontainers) the ArticleService
was injected good. But in test with testcontainers this not injected.
CodePudding user response:
Please check ArticleService class is spring bean or not, means ArticleService class was annoted @Service or @Component annotaion or not. When you apply @Component on a class, then Spring bean container initialize as bean object in Spring Bean Container and Spring Container is trying to inject initialized bean object to annoted @Autowired field. And if you apply @Component on class NullPointerException occurs.
CodePudding user response:
For example this test runs good. And ArticleService
was injected.
@SpringBootTest
public class DemoTest {
@Autowired
private ArticleService articleService;
@Test
public void simpleTest() {
articleService.persistArticle(new ArticleRequestDto());
}
}