使用Mock 对spring mvc 的controller层进行单元测试

总体目标:达到自动化测试接口的目的

项目组成:spring mvc + hibernate + mysql

如何使用mock进行接口的单元测试?

实现思路:将mysql替换成h2数据库,之前hibernate 的datesource配置的是mysql,现在配置成h2,这样测试的数据库是干净的,因为在内存中。每次进行junit mock测试之前清空一下内存中的数据库即可

实现代码:

package cn.edu.hebtu.www.onemeet.client.controller;


import cn.edu.hebtu.www.onemeet.client.model.Company;
import cn.edu.hebtu.www.onemeet.client.model.Department;
import cn.edu.hebtu.www.onemeet.client.model.Me;
import cn.edu.hebtu.www.onemeet.common.model.Reply;
import cn.edu.hebtu.www.onemeet.common.web.filter.EncodeFilter;
import cn.edu.hebtu.www.onemeet.utils.TestUtils;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.jdbc.JdbcTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;


import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;


import javax.sql.DataSource;
import java.util.List;




/**
 * mock测试,使用mock测试来保证接口的正确性
 * Created by chenzhibing on 15-10-30.
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-hibernate-h2.xml"})
public class MockTest {
    private static Logger logger = Logger.getLogger(MockTest.class);
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    private JdbcTemplate template;
    @Autowired
    private EncodeFilter encodeFilter;
    @Autowired
    private OpenSessionInViewFilter openSessionInViewFilter;




    @Autowired
    public void setDataSource(DataSource dataSource) {
        template = new JdbcTemplate(dataSource);
    }


    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(this.encodeFilter, this.openSessionInViewFilter).build();
    }


    @Before
    public void cleanData() {
        String script = "classpath:H2_Init.sql";
        Resource resource = wac.getResource(script);
        JdbcTestUtils.executeSqlScript(template, resource, true);
    }




    @Test
    public void hello() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/user/hello"))
                .andDo(print())
                .andReturn();
        String response = result.getResponse().getContentAsString();
        Reply reply = TestUtils.getStringReply(response);
        assertEquals(reply.getCode(), 1);
    }


    @Test
    public void getCompanylist() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/user/get_companylist"))
                .andDo(print())
                .andReturn();
        String response = result.getResponse().getContentAsString();
        Reply<List<Company>> reply = TestUtils.getCompanyListReply(response);
        assertEquals(reply.getCode(), 1);
        assertEquals(reply.getMsg().size(), 3);
        // assertEquals(reply.getMsg().get(0).getDepartList().size(), 4);
    }
  }

}

你可能感兴趣的:(spring,mvc,JUnit,mock)