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; } }
相关推荐
Spring MVC 是一个强大的Java web开发框架,用于构建可维护、可扩展的...总之,通过正确使用JUnit、Mockito、Spring Test以及MockMVC,我们可以编写出全面、有效的Spring MVC单元测试,确保代码质量并降低潜在的bug。
本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...
在Spring MVC和JPA的开发过程中,单元测试是不可或缺的一部分,它可以帮助我们验证代码的正确性,确保系统各个部分能够按预期工作。本例子聚焦于使用Spring的Test注解进行事务管理的单元测试,这对于数据库操作尤其...
在Spring MVC框架中,单元测试是确保代码质量的重要步骤,特别是在控制器层(Controller)。这篇博客主要探讨了如何使用JUnit进行Spring MVC Controller的单元测试。在实际开发中,单元测试可以帮助我们尽早发现潜在...
Spring MVC提供了MockMVC,可以在不依赖服务器的情况下进行单元测试和集成测试。 这个"最全最经典spring-mvc教程"应该会详细讲解上述所有概念,并可能通过实例演示如何配置、创建和调试Spring MVC项目。对于想要...
十三、如何给Spring3 MVC中的Action做JUnit单元测试:说明了如何对Spring MVC中的控制器进行单元测试,包括配置测试环境和编写测试代码。 十四、Spring MVC转发与重定向:详细讲解了在Spring MVC中如何使用转发和...
#### 七、Spring MVC 单元测试 - **JUnit 测试**:使用 JUnit 和 Mockito 等工具进行单元测试。 - **Mockito**:模拟 Controller 依赖的对象,以确保测试只关注 Controller 的逻辑。 #### 八、Spring MVC 前后端...
在"spring mvc 单元测试 - 记记更好 - 51CTO技术博客.mht"这篇文章中,可能详细介绍了如何设置和使用`MockMvc`进行单元测试,包括配置测试环境、编写测试用例以及断言结果等步骤。 在实际开发中,GuoLong(可能是指...
而JUnit作为Java领域最常用的单元测试框架,可以帮助开发者确保代码的质量和功能的正确性。本测试着重关注Spring MVC架构中的三层:表现层(Presentation Layer)、业务层(Business Logic Layer)和服务数据访问层...
JUnit作为Java领域最流行的单元测试框架,与Spring MVC和Spring Boot的集成使得开发者能够更高效地进行测试驱动开发(TDD)或行为驱动开发(BDD)。下面将详细介绍这个主题中的相关知识点。 1. JUnit JUnit是一个...
9. **单元测试**:利用MockMVC进行Controller层面的单元测试。 10. **源码分析**:通过对Spring MVC源码的阅读和理解,学习其内部工作原理,提升问题排查和性能调优的能力。 以上就是基于提供的信息推测的Spring ...
在Spring Boot框架中,单元测试是一项至关重要的任务,它能够帮助开发者确保代码的正确性和可靠性。Spring Boot提供了方便的工具和库,使得编写和执行单元测试变得简单高效。本章节我们将深入探讨Spring Boot中的...
10. **单元测试和集成测试**:学习如何使用JUnit和Mockito等工具对Controller和Service层进行单元测试,以及使用Spring Test对整个应用进行集成测试。 通过这个简单的例子,初学者可以全面地了解Spring MVC的工作...
Spring MVC提供了MockMvc工具,可以在不启动服务器的情况下进行单元测试和集成测试。 这个“spring MVC_快速入门”文档可能涵盖了以上部分或全部内容,旨在帮助初学者快速理解Spring MVC的工作原理和基本用法。...
在 Spring 中,我们可以使用 `MockMvc` 工具进行单元测试,模拟 HTTP 请求并验证响应结果。 6. **实战案例** - 创建一个简单的 `HelloWorld` 控制器,使用 `@Controller` 注解标记,然后通过 `@RequestMapping` ...
十三、如何给spring3 MVC中的Action做JUnit单元测试? 十四、spring mvc 转发与重定向 十五、spring mvc 处理ajax请求 十六、spring mvc 关于写几个配置文件的说明 十七、spring mvc 如何取得Spring管理的bean 十八...