View Javadoc
1   /**
2    * Copyright 2010-2019 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 static org.assertj.core.api.Assertions.assertThat;
19  
20  import javax.transaction.UserTransaction;
21  
22  import org.junit.jupiter.api.Test;
23  import org.junit.jupiter.api.extension.ExtendWith;
24  import org.springframework.beans.factory.annotation.Autowired;
25  import org.springframework.test.context.junit.jupiter.SpringExtension;
26  import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
27  
28  @ExtendWith(SpringExtension.class)
29  @SpringJUnitConfig(locations = "classpath:org/mybatis/spring/submitted/xa/applicationContext.xml")
30  class UserServiceTest {
31  
32    @Autowired
33    UserTransaction userTransaction;
34  
35    @Autowired
36    private UserService userService;
37  
38    @Test
39    void testCommit() {
40      Userbmitted/xa/User.html#User">User user = new User(1, "Pocoyo");
41      userService.saveWithNoFailure(user);
42      assertThat(userService.checkUserExists(user.getId())).isTrue();
43    }
44  
45    @Test
46    void testRollback() {
47      Userbmitted/xa/User.html#User">User user = new User(2, "Pocoyo");
48      try {
49        userService.saveWithFailure(user);
50      } catch (RuntimeException ignore) {
51        // ignored
52      }
53      assertThat(userService.checkUserExists(user.getId())).isFalse();
54    }
55  
56    @Test
57    void testCommitWithExistingTx() throws Exception {
58      userTransaction.begin();
59      Userbmitted/xa/User.html#User">User user = new User(3, "Pocoyo");
60      userService.saveWithNoFailure(user);
61      userTransaction.commit();
62      assertThat(userService.checkUserExists(user.getId())).isTrue();
63    }
64  
65    // TODO when the outer JTA tx is rolledback,
66    // SqlSession should be rolledback but it is committed
67    // because Spring calls beforeCommmit from its TX interceptor
68    // then, the JTA TX may be rolledback.
69    @Test
70    void testRollbackWithExistingTx() throws Exception {
71      userTransaction.begin();
72      Userbmitted/xa/User.html#User">User user = new User(5, "Pocoyo");
73      userService.saveWithNoFailure(user);
74      userTransaction.rollback();
75      assertThat(userService.checkUserExists(user.getId())).isFalse();
76    }
77  
78  }