Тестирование с помощью Springboot @autowire не работает с @SpringBootTest

Я пишу Junits в приложении springboot, которое имеет только один класс инициализатора как

@SpringBootApplication 

public class Initializer extends SpringBootServletInitializer {

 @Override 
 protected SpringApplicationBuilder configure(SpringApplicationBuilder 
  application) {
      return application.sources(Initializer.class);
   }

 }

и другие классы контроллера и обслуживания.

Мой Junit для класса обслуживания выглядит так:

@RunWith(SpringJUnit4ClassRunner.class)  
@SpringBootTest  
public class ServiceTest {

           @Autowired
            private CommonUtils commonUtils;

             -----do assert cases---------

  }

Когда я запускаю Junit, он выдает ошибку:

    08:20:27.481 [main] ERROR 
    org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1e67b872] to prepare test instance [<ServiceTest>@5d624da6]
    java.lang.IllegalStateException: Failed to load ApplicationContext
        at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies (DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.IllegalArgumentException: Can not load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration.
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:276)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
... 24 common frames omitted 08:20:27.532 [main] DEBUG org.springframework.test.context.support.DirtiesContextTestExecutionListener - After test class: context [[TestContext@2ef9b8bc testClass = ServiceTest, locations = [null], testInstance = [null], testMethod = [null], testException = [null]]], dirtiesContext [false].

Также я пробовал использовать все аннотации, такие как @WebAppConfiguration, @ContextConfiguration (classes = Initializer.class) , @SpringBootConfiguration, @ComponentScan, но все равно выдает ту же ошибку. В коде нет других классов конфигурации, таких как контекст приложения.


person Harsha    schedule 18.04.2018    source источник
comment
попробуйте использовать его с @RunWith(SpringRunner.class) вместо @RunWith(SpringJUnit4ClassRunner.class)   -  person Patrick    schedule 18.04.2018
comment
ты разворачиваешь войну? это старое и традиционное развертывание, некоторые новые функции Spring (реактивные) даже не поддерживают это развертывание ...   -  person shahaf    schedule 18.04.2018
comment
@RunWith (SpringRunner.class) тоже не работал.   -  person Harsha    schedule 18.04.2018
comment
да, мы разворачиваем войну   -  person Harsha    schedule 18.04.2018
comment
В каких пакетах находится ваш тестовый класс и ваш класс загрузочного приложения?   -  person chrylis -cautiouslyoptimistic-    schedule 18.04.2018
comment
имя пакета одинаково для обоих   -  person Harsha    schedule 18.04.2018
comment
@ Патрик не работает   -  person Harsha    schedule 18.04.2018
comment
возможно, это поможет заголовок stackoverflow.com/questions/43078136/   -  person shahaf    schedule 18.04.2018


Ответы (1)


Вы можете протестировать, используя аннотацию @SpringBootTest, со свойством "classes", где вам нужно добавить свой основной класс весенней загрузки:

@SpringBootTest(classes = YOUR_MAIN_CLASS.class, webEnvironment = SpringBootTest.WebEnvironment.NONE)
person Nacho Soriano    schedule 18.04.2018
comment
Я тоже пробовал, мой класс теперь выглядит так: @RunWith (SpringRunner.class) @SpringBootConfiguration @SpringBootTest (classes = Initializer.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) public class ServiceTest {... все равно ошибка та же - person Harsha; 18.04.2018
comment
Вместо @SpringBootConfiguration используйте @TestPropertySource (location = classpath: tests.properties). Это будет результат: @RunWith (SpringRunner.class) @SpringBootTest (classes = Initializer.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) @DirtiesContext (classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestPropertySource: (location) характеристики) - person Nacho Soriano; 18.04.2018
comment
Пожалуйста, @Harsha, не могли бы вы дать отзыв о последнем предложении? - person Nacho Soriano; 19.04.2018
comment
Не работал ни с одним решением, работал с аннотацией @mockito - person Harsha; 27.04.2018