SSM项目Junit单元测试

项目搭建就不重复说了,有不明白的请参考 Maven+Eclipse(STS)搭建SSM项目笔记: https://www.jianshu.com/p/ca0e929c180a。

使用SSM项目测试问题,每次启动容器测试数据层,业务层代码有点麻烦。使用Junit单元测试可以解决每次测试数据层,业务层,控制层的代码测试。直接上代码。

package com.ssm.test;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;


/**
* *测试
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")  
// 只是测试数据层只需要指定mybatis配置文件即可
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml"})
// 业务层测试指定配置文件
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml", "classpath:config/spring/springmvc.xml" })
// 可以使用统配符号 *
@ContextConfiguration({ "classpath:config/spring/*.xml"})
// 事务
@Transactional(transactionManager = "transactionManager")
// 测试结束后事物是否回滚;默认true;
@Rollback(value = false) 
public class AppTest {
    private static final Logger log = Logger.getLogger(AppTest.class);
    @Autowired  
    private WebApplicationContext wac;  
    private MockMvc mockMvc;  
    @Before  
    public void setUp() {  
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  
    }  

    @Test
    public void helloControllerTest() throws Exception {
        log.info("==========访问http://localhost:8080/ssm/hello/index=======================");
        String contentAsString = mockMvc.perform(MockMvcRequestBuilders.get("/hello/index"))
                                        .andReturn()
                                        .getResponse()
                                        .getContentAsString();
        log.info(contentAsString);
    } 
    
    
    @Resource
    private UserMapper userMapper;
    @Test
    public void userMapperSelectByIdTest() {
        log.info("==========测试数据层使用=======================");
        User user = userMapper.selectById(1);
        log.info(user);
    } 
}

是不是很方便呀!如果帮到了你,麻烦老铁点赞!谢谢各位。

你可能感兴趣的:(SSM项目Junit单元测试)