【Spring】コントローラの例外出力テスト
リクエストを受け付けるコントローラのテストは基本的にMockMvc
を使って書くことが多い。
例外を出力をさせる場合、その例外出力のテストはorg.assertj.core.api.Assertions.assertThatThrownBy
で実装できる。
例
プロダクトコード
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping(value = "exception")
public void throwException() {
throw new IllegalStateException("例外です");
}
}
テストコード
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void throwExceptionTest() {
assertThatThrownBy(() ->
mockMvc.perform(get("/exception"))
).hasCause(new IllegalStateException("例外です"));
}
}
.hasCause
を使えば例外の中身を検証できる。
参考
assertThatThrownBy(リファレンス)
How to prevent NestedServletException when testing Spring endpoints?(stack overflow)
Author And Source
この問題について(【Spring】コントローラの例外出力テスト), 我々は、より多くの情報をここで見つけました https://qiita.com/kenduck/items/32451efc873bb65bbe79著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .