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());

	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章