Spring Boot 3 + Testcontainers: интеграционные тесты игнорируются без явной ошибкиJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Spring Boot 3 + Testcontainers: интеграционные тесты игнорируются без явной ошибки

Сообщение Anonymous »

Я запускаю интеграционные тесты с MySQLContainer и @ServiceConnection, но JUnit просто помечает их как «игнорированные/пропущенные», и я не знаю, что делать.
Класс ИТ:
package com.musicStore.api_loja_discos.integration;

import com.musicStore.api_loja_discos.Wrapper.PageableResponse;
import com.musicStore.api_loja_discos.domain.Artist;
import com.musicStore.api_loja_discos.repository.ArtistRepository;
import com.musicStore.api_loja_discos.util.ArtistCreator;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.mysql.MySQLContainer;

@Testcontainers
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ArtistControllerIT {

@Autowired
private TestRestTemplate testRestTemplate;

@Container
@ServiceConnection
private static final org.testcontainers.mysql.MySQLContainer container = new MySQLContainer("mysql:8.0");

@LocalServerPort
private int port;

@Autowired
private ArtistRepository artistRepository;

@Test
@DisplayName("List returns list of artist inside page object when successful")
void list_ReturnsListOfArtistInsidePageObjet_WhenSuccessful() {

Artist saved = artistRepository.save(ArtistCreator.createArtistToBeSaved());

PageableResponse artistPage = testRestTemplate.exchange("/artists/list-artists", HttpMethod.GET, null, new ParameterizedTypeReference
>() {
}).getBody();

org.assertj.core.api.Assertions.assertThat(artistPage).isNotNull();
org.assertj.core.api.Assertions.assertThat(artistPage.getContent()).hasSize(1);
org.assertj.core.api.Assertions.assertThat(artistPage.getContent().get(0).getName()).isEqualTo(saved.getName());
}

@Test
@DisplayName("Should return an artist dto by id when found one")
void shouldReturnAnArtist_WhenPassedId() {

Artist saved = artistRepository.save(ArtistCreator.createValidArtist());

testRestTemplate.exchange("/artists", HttpMethod.GET, null, saved.getClass(), saved.getId());

org.junit.jupiter.api.Assertions.assertEquals(1L, saved.getId(), "ID SHOULD BE 1");
}

// @Test
// @DisplayName("Should throw BadRequestException when artist is not found")
// void shouldTrowBadRequestException_WhenArtistNotFound() {
//
// BDDMockito.given(artistService.findArtistById(any())).willThrow(new BadRequestException("Artist not found"));
//
// org.assertj.core.api.Assertions.assertThatExceptionOfType(BadRequestException.class)
// .isThrownBy(() -> artistController.findByIdOrElseThrow(1L))
// .withMessageContaining("Artist not found");
// }
//
// @Test
// @DisplayName("should replace the artist")
// void shouldReplaceTheGenreOfAnArtist() {
// ArtistPutRequestBody request = ArtistCreator.createArtistPutRequestBody();
// ArtistDTO expectedResponse = ArtistCreator.createValidArtistDTO();

// BDDMockito.given(artistService.replace(ArgumentMatchers.any(ArtistPutRequestBody.class))).willReturn(expectedResponse);

// ResponseEntity response = artistController.replace(request);

// org.assertj.core.api.Assertions.assertThat(response).isNotNull();
// org.assertj.core.api.Assertions.assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
// org.assertj.core.api.Assertions.assertThat(response.getBody().getName()).isEqualTo(expectedResponse.getName());

// }
}

зависимости:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

org.springframework.boot
spring-boot-starter-parent
3.4.5

com.musicStore
api-loja-discos
0.0.1-SNAPSHOT
musicApi
Demo project for Spring Boot














25
1.6.3





org.jspecify
jspecify
1.0.0
compile



org.springframework.boot
spring-boot-starter-web



org.springframework.boot
spring-boot-starter-validation



org.springframework.boot
spring-boot-devtools
runtime
true



com.mysql
mysql-connector-j
runtime



org.projectlombok
lombok
true



org.springframework.boot
spring-boot-starter-test


org.junit.vintage
junit-vintage-engine





org.springframework.boot
spring-boot-testcontainers
test



org.mapstruct
mapstruct
${org.mapstruct.version}




org.testcontainers
junit-jupiter
1.20.5
test




org.testcontainers
testcontainers-mysql
2.0.1
test



org.springframework.boot
spring-boot-starter-data-jpa







org.springframework.boot
spring-boot-maven-plugin



org.projectlombok
lombok






org.apache.maven.plugins
maven-compiler-plugin
3.11.0
${java.version}
${java.version}


org.projectlombok
lombok
${lombok.version}


org.projectlombok
lombok-mapstruct-binding
0.2.0


org.mapstruct
mapstruct-processor
${org.mapstruct.version}










´´´
application-test.yml:
´´´
spring:
datasource:
url: jdbc:tc:mysql:8.4:///testdb
driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver

´´´
Когда я запускаю docker-compose через терминал, он работает. Но испытания даже не начинаются. В журналах я вижу:
java.lang.IllegalStateException: не удалось найти действительную среду Docker. Просмотрите журналы и проверьте конфигурацию
at org.testcontainers.dockerclient.DockerClientProviderStrategy.lambda$getFirstValidStrategy$7(DockerClientProviderStrategy.java:274)
at java.base/java.util.Optional.orElseThrow(Optional.java:403)
at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:265)
at org.testcontainers.DockerClientFactory.getOrInitializeStrategy(DockerClientFactory.java:154)
at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:196)
at org.testcontainers.DockerClientFactory$1.getDockerClient(DockerClientFactory.java:108)
at com.github.dockerjava.api.DockerClientDelegate.authConfig(DockerClientDelegate.java:109)
at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:321)

Suppressed: org.testcontainers.containers.ContainerFetchException: Can't get Docker image: RemoteDockerImage(imageName=mysql:8.4, imagePullPolicy=DefaultPullPolicy(), imageNameSubstitutor=org.testcontainers.utility.ImageNameSubstitutor$LogWrappedImageNameSubstitutor@44cb460e) at org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1364) at org.springframework.boot.testcontainers.service.connection.ServiceConnectionContextCustomizerFactory.createSource(ServiceConnectionContextCustomizerFactory.java:89) at org.springframework.boot.testcontainers.service.connection.ServiceConnectionContextCustomizerFactory.lambda$collectSources$0(ServiceConnectionContextCustomizerFactory.java:64) at org.springframework.core.annotation.TypeMappedAnnotations$AggregatesSpliterator.tryAdvance(TypeMappedAnnotations.java:610) at org.springframework.core.annotation.TypeMappedAnnotations$AggregatesSpliterator.tryAdvance(TypeMappedAnnotations.java:577) at java.base/java.util.Spliterator.forEachRemaining(Spliterator.java:332) at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:803) at org.springframework.boot.testcontainers.service.connection.ServiceConnectionContextCustomizerFactory.lambda$collectSources$1(ServiceConnectionContextCustomizerFactory.java:64) at org.springframework.util.ReflectionUtils.doWithLocalFields(ReflectionUtils.java:691) at org.springframework.boot.testcontainers.service.connection.ServiceConnectionContextCustomizerFactory.collectSources(ServiceConnectionContextCustomizerFactory.java:61) at org.springframework.boot.testcontainers.service.connection.ServiceConnectionContextCustomizerFactory.createContextCustomizer(ServiceConnectionContextCustomizerFactory.java:53) at org.springframework.test.context.support.AbstractTestContextBootstrapper.getContextCustomizers(AbstractTestContextBootstrapper.java:360) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:332) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:267) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:215) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108) at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:111) at org.springframework.test.context.TestContextManager.(TestContextManager.java:142) at org.springframework.test.context.TestContextManager.(TestContextManager.java:126) at org.springframework.test.context.junit.jupiter.SpringExtension.getTestContextManager(SpringExtension.java:362) at org.springframework.test.context.junit.jupiter.SpringExtension.afterAll(SpringExtension.java:139) ... 1 more Caused by: java.lang.IllegalStateException: Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:229) at org.testcontainers.DockerClientFactory.getOrInitializeStrategy(DockerClientFactory.java:154) at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:196) at org.testcontainers.images.LocalImagesCache.get(LocalImagesCache.java:31) at org.testcontainers.images.AbstractImagePullPolicy.shouldPull(AbstractImagePullPolicy.java:18) at org.testcontainers.images.RemoteDockerImage.resolve(RemoteDockerImage.java:79) at org.testcontainers.images.RemoteDockerImage.resolve(RemoteDockerImage.java:35) at org.testcontainers.utility.LazyFuture.getResolvedValue(LazyFuture.java:20) at org.testcontainers.utility.LazyFuture.get(LazyFuture.java:41) at org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1362) ... 21 more
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»