コントローラー内で全く処理がないので、テストは伝統的にブラウザから直接開いてOKとかNGとか確認できますが、今回はテスト・ツールを使ってみます。
src/test/java/demo/DemoControllerTests.javaなるものを作ります。
package demo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@WebAppConfiguration
public class DemoControllerTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void getDemoPage() throws Exception {
ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/demo?name="));
resultActions.andExpect(MockMvcResultMatchers.status().isOk());
resultActions.andExpect(MockMvcResultMatchers.model().attributeDoesNotExist("name"));
}
}
とでも書いておきます。
で、実行します。
DemoControllerTestsを右クリックしてDebug As→JunitTestをクリック
グリーンなら正常、レッドなら異常になるので、常に結果がグリーンになるようにしましょう。
余談ですが、modelのattributeがnullを期待する場合のチェックは以下の様に書いておくと良いです。
resultActions.andExpect(MockMvcResultMatchers.model().attributeDoesNotExist("name"));


0 件のコメント:
コメントを投稿