Spring-mvc junit单元测试中 如何回滚?

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "classpath:./spring/applicationContext.xml")
})
public class MessageTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc; @Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void testTempPage() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/msg/temp/page/v1"));
} @Test
public void testAddTemp() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/msg/temp/add/v1").param("name", "新测试3")
.param("content", "nice roll"));
}
}

testAddTemp添加了一天记录,如何使这个测试添加的动作自动回滚?

 
 

1 个回答

 

1

 
采纳
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "classpath:./spring/applicationContext.xml")
})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class MessageTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc; @Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
} @Test
public void testTempPage() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/msg/temp/page/v1"));
} @Test
@Rollback(true)
public void testAddTemp() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/msg/temp/add/v1").param("name", "新测试3")
.param("content", "nice roll"));
}
}

一般来说在你的测试类上加上@Transactional就足够了,Spring默认是会回滚的。
更简便的做法:直接继承AbstractTransactionalJUnit4SpringContextTests

上一篇:打开SharePoint 2013 web application显示iis 欢迎页面


下一篇:高性能队列Disruptor系列2--浅析Disruptor