SpringBoot1.4-Невозможно найти @SpringBootConfiguration, используйте @ContextConfiguration/ @SpringBootTest (класс) в тестовой ошибке при запуске IntegrationTest

У меня возникла проблема с интеграционным тестом на одном из тестов контроллера в SpringBoot 1.4. Нижеприведенные фрагменты покажут четкое представление о структуре проекта:

класс ExchangeControllerIT:

    public class ExchangeControllerIT extends AbstractSpringControllerIT {

      // class under test
      @Autowired
      private ExchangeController exchangeController;

      @Autowired
      private OAuth2RestTemplate restTemplate;

      @Test
      public void shouldSuccessWhileExchange() throws Exception {
        // given       
        controllerHas(mockExchangeServiceReturningStringResponse());
        // then      
        getMockMvc().perform(get(Uris.Exchange).accept(MediaType.TEXT_HTML)
                .content(asString(ExchangeControllerIT.class, "")))
                .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.parseMediaType(MediaType.TEXT_HTML + ";charset=UTF-8")));        
       }

       private void controllerHas(ExchangeService exchangeService) {
           Reflections.setField(exchangeController, "exchangeService", exchangeService);
       }

       private static ExchangeService mockExchangeServiceReturningStringResponse() {
        return new HandShakeService();           
       }
}

Абстрактный класс ниже:

    public abstract class AbstractSpringControllerIT extends AbstractSpringIT{

       protected MockMvc getMockMvc() {
           return webAppContextSetup(getApplicationContext()).build();
       }
    }

Класс AbstractSpringIT:

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT)
    public abstract class AbstractSpringIT {

       @Autowired(required=true)
       private GenericWebApplicationContext ctx;
       protected final GenericWebApplicationContext getApplicationContext() {
           return ctx;
       }
   }

Я новичок в SpringBoot и тестах, помогите мне найти причину и вероятное решение

StackTrace для вышеупомянутой ошибки:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

at org.springframework.util.Assert.state(Assert.java:392)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:173)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:133)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:409)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:323)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:277)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:112)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:78)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:96)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

person Om Bhakre    schedule 06.03.2017    source источник
comment
Не могли бы вы включить полную трассировку стека?   -  person megalucio    schedule 06.03.2017
comment
@megalucio я добавил stackTrace .. вы можете посмотреть, если это дает какой-либо намек   -  person Om Bhakre    schedule 06.03.2017
comment
В каких пакетах находятся ваши тесты и основной класс приложения?   -  person Andy Wilkinson    schedule 06.03.2017
comment
@AndyWilkinson У меня есть основной и другие классы в com.org.abc, а также resources/com.org.abc и тот же путь для тестовых классов в тестовом каталоге. У меня есть application.properties и applicationContext.xml в resources/com.org.abc как в основном, так и в тестовом каталоге. Appcontext и TestAppContext(который импортирует applicationContext.xml) в com.org.abc/subfolder в основном и тестовом каталогах соответственно.   -  person Om Bhakre    schedule 07.03.2017


Ответы (1)


Похоже, что даже если вы используете аннотацию @SpringBootTest, вы не включаете ее параметр классов, где вам нужно будет указать классы, которые вам нужно будет загрузить в вашем контексте, чтобы ваш тест прошел успешно.

Проверьте, какие классы вам нужны, и включите их туда:

@SpringBootTest(classes=...)

Кроме того, хотя это может быть не лучшим решением, если вы не против перезагрузить весь контекст Spring для своего теста, вы можете просто использовать аннотацию @SpringBootConfiguration в своем тестовом классе вместо @SpringBootTest

person megalucio    schedule 06.03.2017
comment
спасибо megalucio, я попробовал то же самое в классе ExchangeControllerIT, теперь он выдает вложенное исключение: org.springframework.context.ApplicationContextException: невозможно запустить EmbeddedWebApplicationContext из-за отсутствия bean-компонента EmbeddedServletContainerFactory. но в какой из вышеперечисленных классов я должен добавить Аннотация @SpringBootConfiguration - person Om Bhakre; 06.03.2017
comment
Я думаю, что это будет в AbstractSpringControllerIT. Также проверьте мой ответ еще раз, поскольку я изменил свой предыдущий ответ на основе предоставленной трассировки стека. - person megalucio; 06.03.2017
comment
Я попробовал @SpringBootConfiguration на AbstractSpringControllerIT, но это не сработало. - person Om Bhakre; 06.03.2017
comment
Извините, я имел в виду в AbstractSpringIT вместо других аннотаций. - person megalucio; 06.03.2017
comment
Я добавил аннотацию @SpringBootTest(classes=) к классу AbstractSpringIT. Хотя я получил успешную сборку, но с предупреждением об исключении Exception: java.lang.IllegalStateException, выброшенное из UncaughtExceptionHandler в потоке Thread-5 Что это значит?? - person Om Bhakre; 07.03.2017
comment
Согласно Spring Docs, поскольку я использую аннотацию SpringBootTest(classes=), нет необходимости добавлять @SpringBootConfiguration - person Om Bhakre; 07.03.2017
comment
Да, это то, что я имел в виду под заменой в моем комментарии выше... Я только что обновил свой первоначальный ответ, чтобы сделать его более понятным... - person megalucio; 07.03.2017