項目搭建就不重復(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);
}
}
是不是很方便呀!如果幫到了你,麻煩老鐵點贊!謝謝各位。