項(xiàng)目搭建就不重復(fù)說(shuō)了,有不明白的請(qǐng)參考 Maven+Eclipse(STS)搭建SSM項(xiàng)目筆記: http://www.reibang.com/p/ca0e929c180a。
使用SSM項(xiàng)目測(cè)試問(wèn)題苹丸,每次啟動(dòng)容器測(cè)試數(shù)據(jù)層沐悦,業(yè)務(wù)層代碼有點(diǎn)麻煩涎显。使用Junit單元測(cè)試可以解決每次測(cè)試數(shù)據(jù)層摧茴,業(yè)務(wù)層哄褒,控制層的代碼測(cè)試稀蟋。直接上代碼。
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;
/**
* *測(cè)試
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
// 只是測(cè)試數(shù)據(jù)層只需要指定mybatis配置文件即可
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml"})
// 業(yè)務(wù)層測(cè)試指定配置文件
//@ContextConfiguration({ "classpath:config/spring/spring-mybatis.xml", "classpath:config/spring/springmvc.xml" })
// 可以使用統(tǒng)配符號(hào) *
@ContextConfiguration({ "classpath:config/spring/*.xml"})
// 事務(wù)
@Transactional(transactionManager = "transactionManager")
// 測(cè)試結(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("==========訪問(wèn)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("==========測(cè)試數(shù)據(jù)層使用=======================");
User user = userMapper.selectById(1);
log.info(user);
}
}
是不是很方便呀呐赡!如果幫到了你退客,麻煩老鐵點(diǎn)贊!謝謝各位链嘀。