基本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"));
	}
}


你可能感兴趣的:(集成测试,controller测试,spring测试)