码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-05-13 23:02:26      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:

@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

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

标签:

原文地址:http://www.cnblogs.com/liuzy2014/p/5491263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!