1. 程式人生 > >使用spring配合Junit進行單元測試的總結

使用spring配合Junit進行單元測試的總結

最近公司的專案和自己的專案中都用到了spring整合junit進行單元測試,總結一下幾種基本的用法:

1.直接對spring中注入的bean進行測試(以DAO為例):

在測試類上新增@RunWith註解指定使用springJunit的測試執行器,@ContextConfiguration註解指定測試用的spring配置檔案的位置

之後我們就可以注入我們需要測試的bean進行測試,Junit在執行測試之前會先解析spring的配置檔案,初始化spring中配置的bean

複製程式碼
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:spring-config-test.xml"})
public class TestProjectDao { @Autowired ProjectDao projectDao;
@Test
public void testCreateProjectCode(){ long applyTime = System.currentTimeMillis(); Timestamp ts = new Timestamp(applyTime); Map codeMap = projectDao.generateCode("5", "8",ts,"院內"); String projectCode
= (String)codeMap.get("_project_code"); Timestamp apply_time = (Timestamp)codeMap.get("_apply_time"); System.out.print(projectCode); System.out.print(apply_time.toString()); Assert.assertTrue(projectCode.length()==12); }
複製程式碼

2.對springMVC進行測試:

   spring3.2之後出現了org.springframework.test.web.servlet.MockMvc

 類,對springMVC單元測試進行支援

樣例如下:

複製程式碼
package com.jiaoyiping.baseproject;

import com.jiaoyiping.baseproject.privilege.controller.MeunController;
import com.jiaoyiping.baseproject.training.bean.Person;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.ModelAndView;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Created with IntelliJ IDEA.
 * User: 焦一平
 * Date: 14-9-25
 * Time: 下午6:45
 * To change this template use File | Settings | File Templates.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
//@ContextConfiguration(classes = {WebMvcConfig.class, MockDataConfig.class})
@ContextConfiguration(locations={"classpath:/spring/applicationContext.xml", "classpath*:mvc-dispatcher-servlet.xml"})
public class TestMockMvc {

    @Autowired
    private org.springframework.web.context.WebApplicationContext context;
    MockMvc mockMvc;
    @Before
    public void before() {
        //可以對所有的controller來進行測試
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();

        //僅僅對單個Controller來進行測試
       // mockMvc = MockMvcBuilders.standaloneSetup(new MeunController()).build();
    }

    @Test
    public void testGetMenu(){
        try {
            System.out.println("----------------------------");
            ResultActions actions =
            this.mockMvc.perform(get("/menu/manage.action"));
            System.out.println(status());//
            System.out.println(content().toString());
            actions.andExpect(status().isOk());
//            actions.andExpect(content().contentType("text/html"));

            System.out.println("----------------------------");

        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    //從controller裡直接增加使用者(用POST的方式)
    //post("路徑").param("屬性名","屬性值");  用這種方法來構造POST
    @Test
    public void addPerson(){try {
                    ResultActions resultActions =
                    this.mockMvc.perform(post("/person/add")
                    .param("name","用友軟體")
                    .param("age","23")
                    .param("address","北京市永豐屯")
            );

            resultActions.andExpect(status().isOk());
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    //得到Controller層返回的ModelAndView的方法:resultActions.andReturn().getModelAndView().getModel().get("person");



    @Test
    public void getPerson(){
        String id ="297e5fb648b0e6d30148b0e6da6d0000";try {
            ResultActions resultActions = this.mockMvc.perform(post("/person/toEditPerson").param("id",id)).andExpect(status().isOk());
            Assert.assertEquals(23,((Person)(resultActions.andReturn().getModelAndView().getModel().get("person"))).getAge());
            Person person =(Person)(resultActions.andReturn().getModelAndView().getModel().get("person"));
            System.out.println(person.getId());
            System.out.println(person.getName());
            System.out.println(person.getAge());
            System.out.println(person.getAddress());

            Assert.assertEquals(23,person.getAge());


        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
複製程式碼

3.測試RestEasy提供的介面(當使用restEasy提供的rest型別介面的時候會用到)

RestEasy提供了 org.jboss.resteasy.core.Dispatcher類來模擬http請求,並返回資料

這樣,在測試介面的時候就不必啟動容器了

程式碼如下

複製程式碼
/**
 * cn.cmri.pds.controller.TestProjectTagController.java
 * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
 * All rights reserved.
 */
package cn.cmri.pds.controller;

import java.net.URISyntaxException;

import javax.servlet.http.HttpServletResponse;

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.cmri.pds.project.controllor.ProjectTagControllor;
import cn.cmri.pds.project.service.ProjectTagService;

/**
 * <pre>
 * Desc: 
 * @author 焦一平
 * @refactor 焦一平
 * @date   2014年12月10日 下午3:44:03
 * @version 1.0
 * @see  
 * REVISIONS: 
 * Version        Date             Author               Description
 * ------------------------------------------------------------------- 
 * 1.0           2014年12月10日                                   焦一平               1. Created this class. 
 * </pre>  
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring-config-test.xml" })
public class TestProjectTagController {
    @Autowired
    ProjectTagService projectTagService;
    Dispatcher dispatcher;

    @Before
    public void before() {
        ProjectTagControllor projectTagControllor = new ProjectTagControllor();
        projectTagControllor.setProjectTagService(projectTagService);
        dispatcher = MockDispatcherFactory.createDispatcher();
        dispatcher.getRegistry().addSingletonResource(projectTagControllor);
    }

    @Test
    public void testProjectTags() throws URISyntaxException{
        MockHttpRequest request = MockHttpRequest.get("/rest/project/123456/tags");
        MockHttpResponse response = new MockHttpResponse();
        dispatcher.invoke(request, response);
        Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
        Assert.assertEquals("指定的專案不存在", response.getContentAsString());
    }
    

}