• 单元测试代码:SpringTest+JUnit


    /**
     * JUnit单元测试父类,配置了Spring的基础环境。 <br/>
     * 可以作为Controller、Service、Dao单元测试的父类。
     * 
     * @author leiwen@fansunion.cn
     */
    public class JUnitTestBase {
    
     public static XmlWebApplicationContext context = null;
    
     private static HandlerMapping handlerMapping;
     private static HandlerAdapter handlerAdapter;
    
     // /public static String[] CONFIG_FILES = { "classpath:spring-*.xml" };
    
     // public static String[] configs = { "file:src/main/resources/spring-*.xml"
     // };
     public static String[] CONFIG_FILES = { "file:src/main/resources/spring-*.xml" };
    
     /**
      * 读取spring配置文件,初始化上下文。
      */
     @BeforeClass
     public static void setUp() {
      System.out.println("Test start...");
    
      context = new XmlWebApplicationContext();
      context.setConfigLocations(CONFIG_FILES);
    
      MockServletContext msc = new MockServletContext();
      context.setServletContext(msc);
      context.refresh();
      msc.setAttribute(
        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
        context);
    
      handlerMapping = (HandlerMapping) context
        .getBean(DefaultAnnotationHandlerMapping.class);
      handlerAdapter = (HandlerAdapter) context.getBean(context
        .getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);
    
     }
    
     // 执行request对象请求的action
     public ModelAndView excuteAction(HttpServletRequest request,
       HttpServletResponse response) throws Exception {
      // 这里需要声明request的实际类型,否则会报错
      request.setAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING, true);
    
      HandlerExecutionChain chain = handlerMapping.getHandler(request);
      Object handler = chain.getHandler();
      final ModelAndView model = handlerAdapter.handle(request, response,
        handler);
      return model;
     }
    
     @AfterClass
     public static void tearUp() {
      System.out.println("Test end!");
     }
    
    }
    
     
    
    
    
    
    //测试Controller的2种方法
    
     
    
    /**
     * CampaignGroupController单元测试。
     * 
     * @author leiwen@fansunion.cn
     */
    public class FansUnionControllerTestextends JUnitTestBase {
    
     @Test
     public void prevAddCampaignGroup() throws Exception {
      MockHttpServletRequest request = new MockHttpServletRequest();
      MockHttpServletResponse response = new MockHttpServletResponse();
      String requestURI = "/campaignGroup/prevAdd";
      request.setRequestURI(requestURI);
      request.setMethod("POST");
      final ModelAndView mav = this.excuteAction(request, response);
      Assert.assertEquals("createCampaignGroup", mav.getViewName());
    
     }
    
     @Test
     public void prevAddCampaignGroup2() throws Exception {
      CampaignGroupController userController = context.getBean(CampaignGroupController.class);
      MockMvc mockMvc = MockMvcBuilders.standaloneSetup(userController)
        .build();
      ResultActions perform = mockMvc.perform(MockMvcRequestBuilders.post("/campaignGroup/prevAdd"));
      ResultActions andExpect = perform
        .andExpect(MockMvcResultMatchers.status().is(200));
      andExpect
        .andExpect(
          MockMvcResultMatchers.view()
            .name("createCampaignGroup"));
     }
    
    }
    
     
    
    ----需要配置2个bean,测试Controller需要用到
    
    <bean
      class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
     </bean>
     <bean
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
     </bean>
    
     
    
    测试Service(Dao类似)
    
    /**
     * 这种方式 的单元测试,不需要重复指定 资源文件,减少重复。 麻烦的地方在于,需要手动获取bean。
     * 
     * @author leiwen@fansunion.cn
     */
    public class FansUnionServiceTest extends JUnitTestBase {
    
     private static CampaignGroupService campaignGroupService = context
       .getBean(CampaignGroupService.class);
    
     
    
     // 测试add,remove,update方法的时候,已经测试了find?
     @Test
     public void addCampaignGroup() {
      CampaignGroup cg = buildOneGroup();
    
      campaignGroupService.add(cg);
    
      CampaignGroup dbCampaignGroup = campaignGroupService.find(cg.getId());
      Assert.assertEquals(cg, dbCampaignGroup);
      campaignGroupService.delete(cg.getId());
     }
    
     
    
    基于注解的测试
    
    /**
     * 
     * 基于注解的单元测试。
     * 
     * @author leiwen@fansunion.cn
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:spring-mvc-context.xml",
      "classpath:spring-common-context.xml" })
    public class FansUnionServiceTestWithAnnotation {
     
     @Autowired
     private CampaignGroupService campaignGroupService;
     
     /**
      * 根据campaignId获取campaignGroup的name集合<br>
      * 测试场景:<br>
      * 
      */
     @Test
     public void testListCampaignGroupNameByCampaignId(){
      System.out.println("**********");
      System.out.println(campaignGroupService.listCampaignGroupNameByCampaignId(1005899));
     }
    
    }
    
     
    

    参考资料:http://lohasle.iteye.com/blog/1617929

    http://jiuyuehe.iteye.com/blog/1882424

  • 相关阅读:
    IIS大量出现Connections_Refused的错误提示
    SQL分类汇总统计聚合查询
    PHP_保留两位小数并且四舍五入_保留两位小数并且不四舍五入
    忘记Ucenter创始人密码的最快速解决方法
    NetBeans无法使用编码GBK安全地打开该文件
    PHP连续输出字母AZ
    C# 和 Linux 时间戳转换
    php中使用header在下载时乱码问题解决
    PHP获取当前时间、时间戳的各种格式写法汇总[日期时间]
    一些PHP性能优化
  • 原文地址:https://www.cnblogs.com/qitian1/p/6463666.html
Copyright © 2020-2023  润新知