`
sillycat
  • 浏览: 2542603 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Spring3 and REST Integration(IV)Controller JUnit Test and Mock/Servlet

 
阅读更多
Spring3 and REST Integration(IV)Controller JUnit Test and Mock/Servlet

There are 4 different ways to JUnit our REST style JSON data Controller.
Servlet Mock
The first way is to use Servlet Mock. There are 2 base classes needed in our project
The Mock Web Application Loader class will be like these:
package com.sillycat.easyrestserver.core;

import javax.servlet.ServletException;

import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.SourceFilteringListener;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.support.AbstractContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class MockWebApplicationContextLoader extends AbstractContextLoader {

     MockWebApplication configuration;

     static MockServletContext servletContext;

     static MockServletConfig servletConfig;

     static XmlWebApplicationContext webApplicationContext;

     public ApplicationContext loadContext(
               MergedContextConfiguration mergedConfig) throws Exception {
          servletConfig = new MockServletConfig(servletContext,
                    configuration.name());
          servletContext = new MockServletContext(configuration.webapp(),
                    new FileSystemResourceLoader());
          webApplicationContext = new XmlWebApplicationContext();
          webApplicationContext.getEnvironment().setActiveProfiles(
                    mergedConfig.getActiveProfiles());
          servletContext.setAttribute(
                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                    webApplicationContext);
          webApplicationContext.setServletConfig(servletConfig);
          webApplicationContext.setConfigLocations(configuration.locations());

          prepareWebApplicationContext();

          return webApplicationContext;
     }

     public ApplicationContext loadContext(String... locations) throws Exception {
          servletConfig = new MockServletConfig(servletContext,
                    configuration.name());
          servletContext = new MockServletContext(configuration.webapp(),
                    new FileSystemResourceLoader());
          webApplicationContext = new XmlWebApplicationContext();
          servletContext.setAttribute(
                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                    webApplicationContext);
          webApplicationContext.setServletConfig(servletConfig);
          webApplicationContext.setConfigLocations(locations);
          prepareWebApplicationContext();
          return webApplicationContext;
     }

     private void prepareWebApplicationContext() throws ServletException {
          @SuppressWarnings("serial")
          final DispatcherServlet dispatcherServlet = new DispatcherServlet() {
               protected WebApplicationContext createWebApplicationContext(
                         ApplicationContext parent) {
                    return webApplicationContext;
               }
          };
          webApplicationContext
                    .addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
                         public void postProcessBeanFactory(
                                   ConfigurableListableBeanFactory beanFactory) {
                              beanFactory.registerResolvableDependency(
                                        DispatcherServlet.class, dispatcherServlet);
                         }
                    });
          webApplicationContext
                    .addApplicationListener(new SourceFilteringListener(
                              webApplicationContext,
                              new ApplicationListener<ContextRefreshedEvent>() {
                                   public void onApplicationEvent(
                                             ContextRefreshedEvent event) {
                                        dispatcherServlet.onApplicationEvent(event);
                                   }
                              }));
          webApplicationContext.refresh();
          webApplicationContext.registerShutdownHook();
          dispatcherServlet.setContextConfigLocation("");
          dispatcherServlet.init(servletConfig);
     }

     protected String[] generateDefaultLocations(Class<?> clazz) {
          extractConfiguration(clazz);
          return super.generateDefaultLocations(clazz);
     }

     protected String[] modifyLocations(Class<?> clazz, String... locations) {
          extractConfiguration(clazz);
          return super.modifyLocations(clazz, locations);
     }

     private void extractConfiguration(Class<?> clazz) {
          configuration = AnnotationUtils.findAnnotation(clazz,
                    MockWebApplication.class);
          if (configuration == null) {
               throw new IllegalArgumentException("Test class " + clazz.getName()
                         + " must be annotated @MockWebApplication.");
          }
     }

     protected String getResourceSuffix() {
          return "-context.xml";
     }
}


And we will use the mockwebapplication class to hold our annotation configuration:
package com.sillycat.easyrestserver.core;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MockWebApplication {
     String webapp() default "src/main/webapp";

     String name();
   
     String[] locations() default "src/test/test-content.xml";
}


The test class will be like this:
package com.sillycat.easyrestserver.controller;

import java.io.IOException;

import javax.servlet.ServletException;

import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerMapping;

import com.sillycat.easyrestserver.core.MockWebApplication;
import com.sillycat.easyrestserver.core.MockWebApplicationContextLoader;
import com.sillycat.easyrestserver.model.Company;
import com.sillycat.easyrestserver.model.Person;

/**
* mock the servlet and use servlet to test our controller
* servlet.service(mockRequest, mockResponse);
* can not mock the service or manager in controller
* @author karl
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = MockWebApplicationContextLoader.class)
@MockWebApplication(name = "easyrestserver", locations = "classpath:test-context.xml")
public class PersonControllerTest1 {

     @Autowired
     private DispatcherServlet servlet;

     ObjectMapper mapper;
     Person person;
     MockHttpServletRequest mockRequest;
     MockHttpServletResponse mockResponse;

     @Before
     public void setUp() throws ServletException, IOException {
          MockitoAnnotations.initMocks(this);
          mapper = new ObjectMapper();
          person = new Person();
          person.setCompany(new Company());
          person.setId(1);
          person.setPersonName("person1");
        
          mockRequest = new MockHttpServletRequest();
          mockRequest.setAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING,true);
        
          mockResponse = new MockHttpServletResponse();
     }
   

     @Test
     public void get() throws Exception {
          mockRequest.setMethod("GET");
          mockRequest.setRequestURI("/person/1");
          mockRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);
          mockResponse = new MockHttpServletResponse();

          servlet.service(mockRequest, mockResponse);

          Person actualPerson = mapper.readValue(
                    mockResponse.getContentAsString(), Person.class);
          Assert.assertEquals(actualPerson.getId(), person.getId());
     }
   
     @Test
     public void add() throws Exception{
          mockRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);
          mockRequest.setMethod("POST");
         mockRequest.setRequestURI("/person");
       
         String jsonPerson = mapper.writeValueAsString(person);
         mockRequest.setContent(jsonPerson.getBytes());

         servlet.service(mockRequest, mockResponse);
       
         Assert.assertEquals(mockResponse.getStatus(), 200);
          Person actualPerson = mapper.readValue(
                    mockResponse.getContentAsString(), Person.class);
          Assert.assertEquals(actualPerson.getId(), person.getId());
     }
}


The sample project named easyrestserver.

references:
spring 3 and rest
http://hi.baidu.com/luohuazju/blog/item/1fe358ea5da873c0d539c9b4.html
http://hi.baidu.com/luohuazju/blog/item/c380b67f9946421b28388ab7.html
http://hi.baidu.com/luohuazju/blog/item/3b68f609650a37dc3bc763c5.html

tcpdump on mac
http://support.apple.com/kb/HT3994
http://hi.baidu.com/luohuazju/blog/item/da079eb3de7109b2d9335aa5.html

mock test
http://www.iteye.com/topic/828513
http://stackoverflow.com/questions/9138555/spring-framework-test-restful-web-service-controller-offline-i-e-no-server-n
http://stackoverflow.com/questions/1401128/how-to-unit-test-a-spring-mvc-controller-using-pathvariable/2457902#2457902
http://ted-young.googlecode.com/svn/trunk/blog.spring-mvc-integration-testing/
https://github.com/springside/springside4/blob/master/examples/mini-service/src/test/java/org/springside/examples/miniservice/webservice/ws/AccountWebServiceTest.java
https://github.com/SpringSource/spring-test-mvc
http://elf8848.iteye.com/blog/875830
分享到:
评论

相关推荐

    spring MVC junit 单元测试(controller)

    1. **配置测试环境**:引入Spring Test和JUnit相关的依赖,创建一个继承自`AbstractJUnit4SpringContextTests`或`SpringRunner`的测试类。在测试类上使用`@RunWith(SpringRunner.class)`注解启用Spring测试支持,并...

    struts-junit spring-mock spring-test junit的javadoc.jar文档

    struts-junit spring-mock spring-test junit等的javadoc.jar格式的API文档,直接导入Eclipse/MyEclipse/Netbeans等IDE即可实现快速API查询。 包含以下文件: File name -------------------------------------- ...

    Android下使用JUnitTest用例

    3. **设置JUnitTest** 首先,在Android项目中创建一个测试目录,通常位于`app/src/androidTest/java`。然后,在这个目录下创建一个新的Java类,继承自`androidx.test.ext.junit.runners.AndroidJUnit4`。这样,你的...

    spring2 junit3

    标题“spring2 junit3”指的是在Spring框架的第二个主要版本中使用JUnit3进行单元测试的相关内容。这篇博文可能探讨了如何在Spring 2.x时代利用JUnit3进行测试驱动开发(TDD),因为JUnit3是当时广泛使用的Java单元...

    spring-Test,Junit4 jar,和测试代码

    接下来,我们将深入探讨Spring Test与JUnit4的结合使用以及如何通过它们进行测试代码的编写。 首先,Spring Test模块提供了一组测试注解,如`@ContextConfiguration`、`@RunWith(SpringRunner.class)`等,这些注解...

    spring-test and junit 的合集

    分别是两个版本的, 因为spring做单元测试的时候, 是很容易出现版本不兼容的情况, 所以我将我用到的jar包分享出来,zip包中内容:hamcrest-core-1.3、junit4.4、junit-4.12、spring_test2.5.5、spring-test-3.2.0....

    JunitTest

    《深入理解JUnitTest》 JUnitTest是Java编程领域中广泛使用的单元测试框架,它为开发者提供了方便、快捷的方式来编写和执行测试用例,确保代码的质量和功能的正确性。在这个主题中,我们将深入探讨JUnitTest的基本...

    spring-test and junit

    分别是两个版本的, 因为spring做单元测试的时候, 是很容易出现版本不兼容的情况, 所以我将我用到的jar包分享出来,zip包中内容:spring_test2.5.5、spring-test-3.2.0.RELEASE 这个我忘了上传有关于junit的jar ,...

    使用mockito玩转junit test

    在Java开发过程中,单元测试是确保代码质量的重要环节,而JUnit是Java领域广泛使用的单元测试框架。Mockito则是一个强大的模拟框架,它允许我们在测试中创建和配置模拟对象,以便隔离被测试代码并专注于测试单个行为...

    spring-test-junit5, JUnit ( a )的spring TestContext框架扩展( a ).zip

    spring-test-junit5, JUnit ( a )的spring TestContext框架扩展( a ) spring 5测试支持这个项目作为 5的正式 Prototype,在 spring TestContext框架测试支持,并与 SPR-13575结合到 Spring Framework 。 因此,在...

    SSM中进行单元测试Junit4+spring-test所需jar包

    在SSM环境中,使用Junit4和spring-test库进行单元测试是标准做法。下面将详细解释如何使用这两个库以及所需的jar包。 Junit4是Java领域广泛使用的单元测试框架,它提供了一套丰富的注解,使得编写测试用例变得更加...

    junit单元测试及Mock应用,超详细的PPT实战应用

    JUnit5引入了新的注解,如@Test、@BeforeEach、@AfterEach等,使得测试更加灵活和可定制。此外,JUnit5还支持并行测试,提高了测试执行效率。 【Mockito使用】 Mockito是一个强大的Mock框架,它可以创建Mock对象并...

    spring-framework-2.5.6 (含junit-4.4.jar、spring-test.jar)

    《Spring Framework 2.5.6与JUnit 4.4及Spring Test的深度解析》 在软件开发领域,Spring Framework以其强大的依赖注入、面向切面编程(AOP)以及全面的事务管理等功能,成为了Java应用开发的重要基石。而这次我们...

    spring3 and junit4

    《Spring3与JUnit4深度解析》 在Java开发领域,Spring框架和JUnit测试工具是不可或缺的重要组成部分。Spring3.2.8是Spring框架的一个稳定版本,它提供了丰富的功能,包括依赖注入、AOP(面向切面编程)、MVC(模型-...

    spring3 junit 测试 + word

    在这个“spring3 junit 测试”主题中,我们将深入探讨如何在Spring3环境中集成和使用JUnit进行单元测试。Spring3提供了对JUnit的内置支持,允许我们在测试上下文中注入依赖,模拟服务,以及使用其强大的测试支持类。...

    junit common test case just for my test

    标题 "junit common test case just for my test" 提示我们这是一组用 JUnit 编写的通用测试用例,专门用于个人测试目的。 JUnit 的核心概念包括测试类、测试方法和断言。测试类通常扩展自 JUnit 的 `TestCase` 类...

    spring-boot-test示例程序

    本示例程序是关于"Spring Boot Test"的实践,它展示了如何进行Spring Rest Controller的集成测试和单元测试。 1. **Spring Boot Test模块**: Spring Boot提供了测试支持模块,包含`spring-boot-starter-test`,这...

    spring boot Junit4配置

    这包括JUnit4本身,Spring的`spring-test`模块以及Spring Boot的`spring-boot-starter-test`模块。这三个依赖分别提供了JUnit4的基本功能,Spring对测试的支持以及Spring Boot测试相关的工具和配置。以下是添加依赖...

    Spring的MOVE进行Junit单元测试

    在本篇文章中,我们将探讨如何利用Spring的MOVE(Model-View-Controller)架构以及JUnit库来执行单元测试。首先,我们需要理解Spring的MOVE架构: 1. **Model**:这是应用的核心业务逻辑部分,它处理数据和业务规则...

    SpringTest_springtest_spring_java_Framework_

    "SpringTest_springtest_spring_java_Framework_"这个标题暗示了我们讨论的是关于Spring框架的测试方面,可能是使用Spring进行单元测试或集成测试的一些实践。 描述中的“简单小应用,实现了一些基本的功能”可能是...

Global site tag (gtag.js) - Google Analytics