• 单元测试代码: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

  • 相关阅读:
    【转】五笔字根图
    数据集ds 转化为json
    js 计算 往前(后)几天(月、年)
    js 每秒刷新系统时间,可停止
    如何获取枚举字符串,值及遍历枚举
    js 正则判断值
    C#将时间格式 yyyymmdd hh:mm:ss转换为yyyyMMddHHmmss
    【转】什么是程序集?
    C# 两个日期相减得到月数和天数和时and计算 日期减去月之后的日期
    js判断一个下拉框的选中值是否改变
  • 原文地址:https://www.cnblogs.com/qitian1/p/6463667.html
Copyright © 2020-2023  润新知