View Javadoc
1   /**
2    *    Copyright 2010-2015 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.spring.submitted.xa;
17  
18  import javax.transaction.UserTransaction;
19  
20  import org.junit.Assert;
21  import org.junit.Test;
22  import org.junit.runner.RunWith;
23  import org.springframework.beans.factory.annotation.Autowired;
24  import org.springframework.test.context.ContextConfiguration;
25  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
26  
27  @RunWith(value = SpringJUnit4ClassRunner.class)
28  @ContextConfiguration(locations = "classpath:org/mybatis/spring/submitted/xa/applicationContext.xml")
29  public class UserServiceTest {
30  
31    @Autowired UserTransaction userTransaction;
32    
33    @Autowired
34    private UserService userService;
35    
36    @Test
37    public void testCommit() {
38      User user = new User(1, "Pocoyo");
39      userService.saveWithNoFailure(user);
40      Assert.assertTrue(userService.checkUserExists(user.getId()));
41    }
42    
43    @Test
44    public void testRollback() {
45      User user = new User(2, "Pocoyo");
46      try {
47        userService.saveWithFailure(user);
48      } catch (RuntimeException ignore) {
49        // ignored
50      }
51      Assert.assertFalse(userService.checkUserExists(user.getId()));
52    }
53  
54    @Test
55    public void testCommitWithExistingTx() throws Exception {
56      userTransaction.begin();
57      User user = new User(3, "Pocoyo");
58      userService.saveWithNoFailure(user);
59      userTransaction.commit();
60      Assert.assertTrue(userService.checkUserExists(user.getId()));
61    }
62  
63    // TODO when the outer JTA tx is rolledback, 
64    // SqlSession should be rolledback but it is committed
65    // because Spring calls beforeCommmit from its TX interceptor
66    // then, the JTA TX may be rolledback.
67    @Test
68    public void testRollbackWithExistingTx() throws Exception {
69      userTransaction.begin();
70      User user = new User(5, "Pocoyo");
71      userService.saveWithNoFailure(user);
72      userTransaction.rollback();
73      Assert.assertFalse(userService.checkUserExists(user.getId()));
74    }
75    
76  }