1. 程式人生 > >Juit4整合SpringMVC,單元測試Controller

Juit4整合SpringMVC,單元測試Controller

1.說明:本文采用的Springboot的開發環境。一般對Service、DAO層的Juit的測試,相對簡單,僅針對controller做探討。

2.測試@ResponseBody,針對controller只放回資料進行測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisApplicationTests {

	@Autowired
	private UserController userController;

	private MockMvc mockMvc;

	@Before
	public void setUp() {
		mockMvc = MockMvcBuilders.standaloneSetup(userController)
				.build();			
	}
	@Test
	public void Ctest() throws Exception {
		ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("/user/all"));
		MvcResult mvcResult = resultActions.andReturn();
		//獲取請求響應的資料
		String result = mvcResult.getResponse().getContentAsString();
		System.out.println(mvcResult.getResponse().getStatus());
	}
}

3.測試MVC的型別

之前參照網上的例子,進行測試,發現出現了異常,但是詭異的是在瀏覽器卻能正常執行,在配置檔案裡也設定了MVC的返回的檢視地址,以及View的型別

javax.servlet.ServletException: Circular view path [add]: would dispatch back to the current handler URL [/user/add] again

查找了一些資料,分析原因是預設轉發,View name與path,Spring的轉發規則,自己轉給自己。

解決辦法1:設定InternalResourceViewResolver,消除預設轉發所帶來的問題

解決辦法2:將請求的Url設定和與返回的view name不同,如上的只需將/user/add 修改成/user/save 即可解決,方法二修改起來更簡單,但是需要根據專案的實際情況來選擇,親測兩種方式都可用。

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisApplicationTests {

	@Autowired
	private UserController userController;

	private MockMvc mockMvc;

	@Before
	public void setUp() {

		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".html");

		mockMvc = MockMvcBuilders.standaloneSetup(userController)
				.setViewResolvers(viewResolver)
				.build();
	}


	@Test
	public void Ctest() throws Exception {
		ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("/user/all"));
		MvcResult mvcResult = resultActions.andReturn();
		ModelAndView modelandView = mvcResult.getModelAndView();
		//對比返回的檢視
		ModelAndViewAssert.assertViewName(modelandView,"add");
		//列印返回的資料
		System.out.println(modelandView.getModel());

	}

}