欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring MVC的单元测试

程序员文章站 2022-06-04 15:31:25
...

Original link:http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-normal-controllers/

翻译地址:http://www.cnblogs.com/zemliu/archive/2013/10/14/3367055.html

 

我自己写的例子:

 

public class PlayerControllerTest extends SpringWebTestCase {

	private MockMvc mockMvc;
	
	@Autowired
	private PlayerController controller;

	@Before
	public void setUp() {
		mockMvc = standaloneSetup(controller).build();
	}

	@Test
	public void testRegister() throws Exception {
		MockHttpServletRequestBuilder mock = post("/register");
		mock.contentType(MediaType.APPLICATION_FORM_URLENCODED)
			.param("loginId", "peak")
			.param("name", "gogogo")
			.param("password", "111")
			.param("mobile", "139")
			.param("email", "peak@eastseven.com");
		mockMvc.perform(mock)
			.andExpect(status().isOk())
			.andExpect(content().contentType("application/json;charset=UTF-8"))
			.andExpect(content().json("{\"success\":true,\"message\":\"操作成功\"}"))
			.andDo(print())
			.andReturn();
	}
}

为了简化静态引入,把父类里面加入了所有mock的方法进来,用的是Jackson

import java.net.URI;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.xml.xpath.XPathExpressionException;

import org.hamcrest.Matcher;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.ContentResultMatchers;
import org.springframework.test.web.servlet.result.CookieResultMatchers;
import org.springframework.test.web.servlet.result.FlashAttributeResultMatchers;
import org.springframework.test.web.servlet.result.HandlerResultMatchers;
import org.springframework.test.web.servlet.result.HeaderResultMatchers;
import org.springframework.test.web.servlet.result.JsonPathResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.ModelResultMatchers;
import org.springframework.test.web.servlet.result.RequestResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
import org.springframework.test.web.servlet.result.ViewResultMatchers;
import org.springframework.test.web.servlet.result.XpathResultMatchers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-mvc.xml" })
public class SpringWebTestCase extends SpringTransactionalTestCase {
	
	public static MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables) {
		return MockMvcRequestBuilders.get(urlTemplate, urlVariables);
	}

	public static MockHttpServletRequestBuilder get(URI uri) {
		return MockMvcRequestBuilders.get(uri);
	}

	public static MockHttpServletRequestBuilder post(String urlTemplate, Object... urlVariables) {
		return MockMvcRequestBuilders.post(urlTemplate, urlVariables);
	}

	public static MockHttpServletRequestBuilder post(URI uri) {
		return MockMvcRequestBuilders.post(uri);
	}
	
	public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, String urlTemplate, Object... urlVariables) {
		return MockMvcRequestBuilders.request(httpMethod, urlTemplate, urlVariables);
	}

	public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, URI uri) {
		return MockMvcRequestBuilders.request(httpMethod, uri);
	}

	public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables) {
		return MockMvcRequestBuilders.fileUpload(urlTemplate, urlVariables);
	}

	public static MockMultipartHttpServletRequestBuilder fileUpload(URI uri) {
		return MockMvcRequestBuilders.fileUpload(uri);
	}

	public static RequestBuilder asyncDispatch(final MvcResult mvcResult) {
		return MockMvcRequestBuilders.asyncDispatch(mvcResult);
	}

	public static ResultHandler print() {
		return MockMvcResultHandlers.print();
	}
	
	public static DefaultMockMvcBuilder webAppContextSetup(WebApplicationContext context) {
		return MockMvcBuilders.webAppContextSetup(context);
	}

	public static StandaloneMockMvcBuilder standaloneSetup(Object... controllers) {
		return MockMvcBuilders.standaloneSetup(controllers);
	}
	
	public static RequestResultMatchers request() {
		return MockMvcResultMatchers.request();
	}

	public static HandlerResultMatchers handler() {
		return MockMvcResultMatchers.handler();
	}

	public static ModelResultMatchers model() {
		return MockMvcResultMatchers.model();
	}

	public static ViewResultMatchers view() {
		return MockMvcResultMatchers.view();
	}

	public static FlashAttributeResultMatchers flash() {
		return MockMvcResultMatchers.flash();
	}

	public static ResultMatcher forwardedUrl(final String expectedUrl) {
		return MockMvcResultMatchers.forwardedUrl(expectedUrl);
	}

	public static ResultMatcher forwardedUrlPattern(final String urlPattern) {
		return MockMvcResultMatchers.forwardedUrlPattern(urlPattern);
	}

	public static ResultMatcher redirectedUrl(final String expectedUrl) {
		return MockMvcResultMatchers.redirectedUrl(expectedUrl);
	}

	public static ResultMatcher redirectedUrlPattern(final String expectedUrl) {
		return MockMvcResultMatchers.redirectedUrlPattern(expectedUrl);
	}

	public static StatusResultMatchers status() {
		return MockMvcResultMatchers.status();
	}

	public static HeaderResultMatchers header() {
		return MockMvcResultMatchers.header();
	}

	public static ContentResultMatchers content() {
		return MockMvcResultMatchers.content();
	}

	public static JsonPathResultMatchers jsonPath(String expression, Object ... args) {
		return MockMvcResultMatchers.jsonPath(expression, args);
	}

	public static <T> ResultMatcher jsonPath(String expression, Matcher<T> matcher) {
		return MockMvcResultMatchers.jsonPath(expression, matcher);
	}

	public static XpathResultMatchers xpath(String expression, Object... args) throws XPathExpressionException {
		return MockMvcResultMatchers.xpath(expression, args);
	}

	public static XpathResultMatchers xpath(String expression, Map<String, String> namespaces, Object... args)
			throws XPathExpressionException {

		return MockMvcResultMatchers.xpath(expression, namespaces, args);
	}

	public static CookieResultMatchers cookie() {
		return MockMvcResultMatchers.cookie();
	}
	
	public byte[] convertObjectToFormUrlEncodedBytes(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		@SuppressWarnings("unchecked")
		Map<String, Object> propertyValues = mapper.convertValue(object, Map.class);
		Set<String> propertyNames = propertyValues.keySet();
		Iterator<String> nameIter = propertyNames.iterator();

		StringBuilder formUrlEncoded = new StringBuilder();

		for (int index = 0; index < propertyNames.size(); index++) {
			String currentKey = nameIter.next();
			Object currentValue = propertyValues.get(currentKey);

			formUrlEncoded.append(currentKey);
			formUrlEncoded.append("=");
			formUrlEncoded.append(currentValue);

			if (nameIter.hasNext()) {
				formUrlEncoded.append("&");
			}
		}

		return formUrlEncoded.toString().getBytes();
	}
}

 

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import javax.sql.DataSource;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

@DirtiesContext
@ContextConfiguration(locations = { "classpath*:/spring-core.xml"})
public abstract class SpringTransactionalTestCase extends AbstractTransactionalJUnit4SpringContextTests {

	protected static final Logger log = LoggerFactory.getLogger(SpringTransactionalTestCase.class);

	protected DataSource dataSource;

	@Override
	@Autowired
	public void setDataSource(DataSource dataSource) {
		super.setDataSource(dataSource);
		this.dataSource = dataSource;
	}
	
	protected <T> T creatRandomObject(Class<T> clazz, String... excludeFieldNames) {
		T obj = null;
		try {
			obj = clazz.newInstance();
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz, IdEntity.class);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor descriptor : propertyDescriptors) {
				if ("class".equals(descriptor.getName()) || ArrayUtils.contains(excludeFieldNames, descriptor.getName())) {
					continue;
				}
				if (BeanUtils.isSimpleValueType(descriptor.getPropertyType())) {
					Object value = ConvertUtils.convert(RandomStringUtils.random(1, false, true), descriptor.getPropertyType());
					Method writeMethod = descriptor.getWriteMethod();
					if (writeMethod != null) {
						writeMethod.invoke(obj, value);
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return obj;
	}
}