Spring Bootコントローラーの単体テスト:ApplicationContextのロードに失敗しました

Thach Huynh

単純なSpringBoot Controllerがあり、その単体テストを作成したいのですが、エラーが発生します。私は何時間もグーグルで検索しましたが、それでも解決策を見つけることができません。コードは次のとおりです。

HelloController.java

@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String sayHello(){
        return helloService.sayHello();
    }
}

HelloService.java:

@Service
public class HelloService {
    public String sayHello(){
        return "Hello";
    }
}

そしてユニットテストファイル:HelloControllerTest.java:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Mock
    private HelloService helloService;


    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void sayHello() throws Exception {
        when(helloService.sayHello()).thenReturn("thach");
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("thach"));
    }

}

しかし、エラーがあります:

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration or @ContextHierarchy.
    at org.springframework.util.Assert.notNull(Assert.java:134)
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:57)
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
    ... 24 more

誰かが私を助けることができますか?私はSpringBootの初心者です

Shashank Bodkhe

私も同様の問題を抱えていました。以下のコードを参照してください。

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationControllerTest {

@Autowired
MockMvc mockMvc;
@MockBean
ApplicationService applicationService;

@Test
public void testGetImagePath() throws Exception {

    RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/application/get-image")
            .contentType(MediaType.IMAGE_GIF);

    MvcResult result = mockMvc.perform(requestBuilder).andReturn();
    System.out.println(result.getResponse());

}

以下のテストケースの実行を参照してください。

テストケース画像

使用したアノテーションを確認してください。例:1)@RunWith(SpringRunner.class)2)@SpringBootTest 3)@AutoConfigureMockMvc

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Spring Bootを使用しないJava Springテスト-エラーjava.lang.IllegalStateException:ApplicationContextのロードに失敗しました

分類Dev

Spring Bootを使用しないJava Springテスト-エラーjava.lang.IllegalStateException:ApplicationContextのロードに失敗しました

分類Dev

ApplicationContextのロードに失敗しました:Springとjunit

分類Dev

依存関係が失敗したSpringコントローラーのテスト

分類Dev

Spring Boot DataJpaTest(リポジトリ用)がjava.lang.IllegalStateException:ApplicationContextのロードに失敗して失敗する

分類Dev

Spring-Webflux:ハンドラー関数の単体テストがUnsupportedMediaTypeStatusExceptionをスローしています

分類Dev

Spring BootテストでApplicationContextをロードできませんでした

分類Dev

Aroundアノテーションが欠落しているため、Spring BootTestはApplicationContextのロードに失敗しました

分類Dev

Springブート統合テストの実行時にApplicationContextをロードできませんでした

分類Dev

SpringがプロパティをロードするPropertyServiceクラスのBeanを作成できないため、MockitoとjUnit5を使用したSpringBootコントローラーテストが失敗しますか?

分類Dev

Springエラー-コンテキストの初期化に失敗しました:org.springframework.beans.factory.BeanCreationException

分類Dev

コンテキストの初期化に失敗しました。Spring エラー NoSuchMethodException

分類Dev

Spring Bootがリソースのロードに失敗しました:サーバーがステータス404で応答しました

分類Dev

Spring Bootがリソースのロードに失敗しました:サーバーがステータス404で応答しました

分類Dev

クラス「org.slf4j.impl.StaticLoggerBinder」のロードに失敗しました、Spring Boot

分類Dev

Spring WebFluxおよびコントローラーでのテストの失敗

分類Dev

Spring Boot:クラスorg.springframework.cloud.netflix.zuul.ZuulConfigurationのアノテーション付きメソッドのイントロスペクトに失敗しました

分類Dev

Spring RESTコントローラーは単体テストで異なる動作をします

分類Dev

Spring Boot Rest APIは、Tomcat 8.5.47に「org.apache.catalina.LifecycleException:コンポーネントの起動に失敗しました」とデプロイされません。

分類Dev

WildflyにデプロイされたSpringブートアプリケーション「WebApplicationInitializerクラスのインスタンス化に失敗しました」

分類Dev

コントローラーの単体テスト時にSpring Validatorをモックする

分類Dev

Spring Boot、kotlin、junitを使用したRESTコントローラーユニットのテスト

分類Dev

Spring Boot:ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.NoSuchMethodErrorです

分類Dev

Spring Boot:ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.NoSuchMethodErrorです

分類Dev

Spring Boot:ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.NoSuchMethodErrorです

分類Dev

Hibernateは、spring-bootおよびspring-data-jpaでロードされると、JPA 2.1コンバーターのロードに失敗します

分類Dev

MockMVCを使用したSpring4.0.3コントローラー(MVC)のテスト

分類Dev

mockitoを使用したSpringでのテスト方法コントローラー

分類Dev

Spring Boot「CommandLineRunnerエラーの実行に失敗しました」

Related 関連記事

  1. 1

    Spring Bootを使用しないJava Springテスト-エラーjava.lang.IllegalStateException:ApplicationContextのロードに失敗しました

  2. 2

    Spring Bootを使用しないJava Springテスト-エラーjava.lang.IllegalStateException:ApplicationContextのロードに失敗しました

  3. 3

    ApplicationContextのロードに失敗しました:Springとjunit

  4. 4

    依存関係が失敗したSpringコントローラーのテスト

  5. 5

    Spring Boot DataJpaTest(リポジトリ用)がjava.lang.IllegalStateException:ApplicationContextのロードに失敗して失敗する

  6. 6

    Spring-Webflux:ハンドラー関数の単体テストがUnsupportedMediaTypeStatusExceptionをスローしています

  7. 7

    Spring BootテストでApplicationContextをロードできませんでした

  8. 8

    Aroundアノテーションが欠落しているため、Spring BootTestはApplicationContextのロードに失敗しました

  9. 9

    Springブート統合テストの実行時にApplicationContextをロードできませんでした

  10. 10

    SpringがプロパティをロードするPropertyServiceクラスのBeanを作成できないため、MockitoとjUnit5を使用したSpringBootコントローラーテストが失敗しますか?

  11. 11

    Springエラー-コンテキストの初期化に失敗しました:org.springframework.beans.factory.BeanCreationException

  12. 12

    コンテキストの初期化に失敗しました。Spring エラー NoSuchMethodException

  13. 13

    Spring Bootがリソースのロードに失敗しました:サーバーがステータス404で応答しました

  14. 14

    Spring Bootがリソースのロードに失敗しました:サーバーがステータス404で応答しました

  15. 15

    クラス「org.slf4j.impl.StaticLoggerBinder」のロードに失敗しました、Spring Boot

  16. 16

    Spring WebFluxおよびコントローラーでのテストの失敗

  17. 17

    Spring Boot:クラスorg.springframework.cloud.netflix.zuul.ZuulConfigurationのアノテーション付きメソッドのイントロスペクトに失敗しました

  18. 18

    Spring RESTコントローラーは単体テストで異なる動作をします

  19. 19

    Spring Boot Rest APIは、Tomcat 8.5.47に「org.apache.catalina.LifecycleException:コンポーネントの起動に失敗しました」とデプロイされません。

  20. 20

    WildflyにデプロイされたSpringブートアプリケーション「WebApplicationInitializerクラスのインスタンス化に失敗しました」

  21. 21

    コントローラーの単体テスト時にSpring Validatorをモックする

  22. 22

    Spring Boot、kotlin、junitを使用したRESTコントローラーユニットのテスト

  23. 23

    Spring Boot:ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.NoSuchMethodErrorです

  24. 24

    Spring Boot:ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.NoSuchMethodErrorです

  25. 25

    Spring Boot:ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.NoSuchMethodErrorです

  26. 26

    Hibernateは、spring-bootおよびspring-data-jpaでロードされると、JPA 2.1コンバーターのロードに失敗します

  27. 27

    MockMVCを使用したSpring4.0.3コントローラー(MVC)のテスト

  28. 28

    mockitoを使用したSpringでのテスト方法コントローラー

  29. 29

    Spring Boot「CommandLineRunnerエラーの実行に失敗しました」

ホットタグ

アーカイブ