Аннотация @SpringBootTest и запуск теста одного класса с помощью встроенного в IDEA средства запуска JUnit вместо цели тJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Аннотация @SpringBootTest и запуск теста одного класса с помощью встроенного в IDEA средства запуска JUnit вместо цели т

Сообщение Anonymous »

У меня есть класс тестирования Java, использующий весенний загрузочный тест:

Код: Выделить всё

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = LvgMainTest.class)
@ActiveProfiles(value = {"integration-test", "test"})
public class ProduitsApiImplTest {

@Autowired
private TestRestTemplate restTemplate;

@Test
public void testListProduits_200_OK() {
Produit produitExpected = new Produit();
produitExpected.setId(1L);
produitExpected.setCode("FFL");
produitExpected.setLibelle("premierProduit");
ResponseEntity
 response = this.restTemplate.getForEntity("/produits?nomOuCode=premier", ProduitSk[].class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotEmpty();
assertThat(response.getBody().length).isEqualTo(1);
assertProduit(response.getBody()[0], produitExpected);
}
Когда я запускаю команду mvn test через IDEA, запускаю конфигурацию «maven» (с целевым тестом). Мой тест пройден!
Но когда я использую в редакторе стрелку на поле слева от имени класса, I.E. при работе со встроенным IDEA Junit у меня возникла ошибка:

Код: Выделить всё

java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@538d2308 testClass = fr.lvg.ProduitsApiImplTest, locations = [], classes = [fr.lvg.LvgMainTest], contextInitializerClasses = [], activeProfiles = ["integration-test", "test"], propertySourceDescriptors = [], propertySourceProperties = ["org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true", "server.port=0"], contextCustomizers = [[ImportsContextCustomizer@3d0697da key = [config.ConfigTest]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@79dc5318, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@54eb2b70, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@50de186c, org.springframework.boot.test.web.reactor.netty.DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactory$DisableReactorResourceFactoryGlobalResourcesContextCustomizerCustomizer@36cda2c2, org.springframework.boot.test.autoconfigure.OnFailureConditionReportContextCustomizerFactory$OnFailureConditionReportContextCustomizer@5b367418, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizer@172b013, org.springframework.boot.test.context.SpringBootTestAnnotation@e306c040], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:180)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.j
....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IProduitMapperImpl' defined in file [D:\travail\workspace-lvg\levidegrenier\lvg-service-impl\target\classes\fr\lvg\mapper\IProduitMapperImpl.class]: Failed to instantiate [fr.lvg.mapper.IProduitMapperImpl]: Constructor threw exception
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1337)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [fr.lvg.mapper.IProduitMapperImpl]: Constructor threw exception
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:221)
...
Caused by: java.lang.Error: Unresolved compilation problems:
IProduitMapper cannot be resolved to a type
The method produitSkToProduit(ProduitSk) of type IProduitMapperImpl must override or implement a supertype method
The method produitToProduitSk(Produit) of type IProduitMapperImpl must override or implement a supertype method

at fr.lvg.mapper.IProduitMapperImpl.(IProduitMapperImpl.java:14)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:195)
... 42 more
Можете ли вы объяснить мне, почему и что нужно сделать, чтобы контейнер SpringBoot запускался в любом случае: mvn test или junit запущен. Кажется, что пути к классам различаются в зависимости от программы запуска (mvn test или встроенный junit).
Спасибо за ваши объяснения.

Подробнее здесь: https://stackoverflow.com/questions/792 ... a-embedded
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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