69

予期しない例外をキャッチするための次の単純なコントローラーがあります。

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity handleException(Throwable ex) {
        return ResponseEntityFactory.internalServerErrorResponse("Unexpected error has occurred.", ex);
    }
}

Spring MVC テスト フレームワークを使用して統合テストを作成しようとしています。これは私がこれまでに持っているものです:

@RunWith(MockitoJUnitRunner.class)
public class ExceptionControllerTest {
    private MockMvc mockMvc;

    @Mock
    private StatusController statusController;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new ExceptionController(), statusController).build();
    }

    @Test
    public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception {

        when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception"));

        mockMvc.perform(get("/api/status"))
                .andDo(print())
                .andExpect(status().isInternalServerError())
                .andExpect(jsonPath("$.error").value("Unexpected Exception"));
    }
}

ExceptionController とモックの StatusController を Spring MVC インフラストラクチャに登録します。テスト メソッドでは、StatusController から例外をスローするように期待を設定します。

例外がスローされていますが、ExceptionController はそれを処理していません。

ExceptionController が例外を取得し、適切な応答を返すことをテストできるようにしたいと考えています。

これが機能しない理由と、この種のテストをどのように行うべきかについての考えはありますか?

ありがとう。

4

6 に答える 6

2

スタンドアロンのセットアップ テストを使用しているため、例外ハンドラを手動で提供する必要があります。

mockMvc= MockMvcBuilders.standaloneSetup(adminCategoryController).setSingleView(view)
        .setHandlerExceptionResolvers(getSimpleMappingExceptionResolver()).build();

私は数日前に同じ問題を抱えていました。Spring MVC Controller Exception Testで私の問題と解決策が自分で答えられていることがわかります。

私の答えがあなたを助けることを願っています

于 2013-08-22T00:58:51.203 に答える
-1

これの方が良い:

((HandlerExceptionResolverComposite) wac.getBean("handlerExceptionResolver")).getExceptionResolvers().get(0)

@Configuration クラスで @ControllerAdvice Bean をスキャンすることを忘れないでください。

@ComponentScan(basePackages = {"com.company.exception"})

...Spring 4.0.2.RELEASEでテスト済み

于 2016-02-23T07:05:03.173 に答える
-2

それを試してみてください;

@RunWith(value = SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { MVCConfig.class, CoreConfig.class, 
        PopulaterConfiguration.class })
public class ExceptionControllerTest {

    private MockMvc mockMvc;

    @Mock
    private StatusController statusController;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception {

        when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception"));

        mockMvc.perform(get("/api/status"))
                .andDo(print())
                .andExpect(status().isInternalServerError())
                .andExpect(jsonPath("$.error").value("Unexpected Exception"));
    }
}
于 2014-02-05T21:23:46.350 に答える