SSM項目Junit單元測試

項目搭建就不重復(fù)說了,有不明白的請參考 Maven+Eclipse(STS)搭建SSM項目筆記: http://www.itdecent.cn/p/ca0e929c180a。

使用SSM項目測試問題,每次啟動容器測試數(shù)據(jù)層,業(yè)務(wù)層代碼有點麻煩。使用Junit單元測試可以解決每次測試數(shù)據(jù)層,業(yè)務(wù)層,控制層的代碼測試。直接上代碼。

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")  
// 只是測試數(shù)據(jù)層只需要指定mybatis配置文件即可
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml"})
// 業(yè)務(wù)層測試指定配置文件
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml", "classpath:config/spring/springmvc.xml" })
// 可以使用統(tǒng)配符號 *
@ContextConfiguration({ "classpath:config/spring/*.xml"})
// 事務(wù)
@Transactional(transactionManager = "transactionManager")
// 測試結(jié)束后事物是否回滾;默認(rèn)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("==========測試數(shù)據(jù)層使用=======================");
        User user = userMapper.selectById(1);
        log.info(user);
    } 
}

是不是很方便呀!如果幫到了你,麻煩老鐵點贊!謝謝各位。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容