首页 > 代码库 > 基本spring测试框架的测试demo
基本spring测试框架的测试demo
以下是user 控制器的测试实例
import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import javassist.expr.NewArray; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; 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.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.controller.user.UserController; import com.entity.user.User; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; import static org.hamcrest.Matchers.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:/spring/spring.applicationContext.mysql.xml"}) public class TestUserController { private MockMvc mockMvc; @Before public void setUp() { this.mockMvc = standaloneSetup(new UserController()) .defaultRequest(get("/") .accept(MediaType.APPLICATION_JSON)) .alwaysExpect(status().isOk()) .alwaysExpect(content().contentType("application/json;charset=UTF-8")) .build(); } @Test public void testDisplayUser() throws Exception { this.mockMvc.perform(get("/users")) .andExpect(view().name("userListView")) .andExpect(model().attribute("users",hasSize(2))) .andExpect(model().attribute("users",hasItem(hasProperty("no", is("FF0478"))))) .andExpect(model().attribute("users",hasItem(hasProperty("no", is("FF0479"))))) .andDo(print()); } @Test public void getUser() throws Exception{ this.mockMvc.perform(get("/users/5476")) .andExpect(model().attribute("user",hasProperty("no", is("FF0830")))) .andExpect(model().attribute("user", hasProperty("id", is(5476)))); } @Test public void saveUser() throws Exception{ this.mockMvc.perform(get("/user/save") .param("name", "李阳") .param("no", "FF0833") .param("password", "123") .param("departmentId", "101")) .andExpect(view().name("userList")); } @Test public void updateUser() throws Exception { this.mockMvc.perform(get("/users/update") .param("id", "12") .param("name", "李阳") .param("no", "FF0834")) .andExpect(view().name("userList")); } }
基本spring测试框架的测试demo
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。