View Javadoc
1   /*
2    *    Copyright 2009-2023 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    *       https://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.apache.ibatis.transaction.jdbc;
17  
18  import static org.junit.Assert.assertEquals;
19  import static org.mockito.Mockito.mock;
20  import static org.mockito.Mockito.when;
21  
22  import javax.sql.DataSource;
23  
24  import org.apache.ibatis.session.TransactionIsolationLevel;
25  import org.junit.jupiter.api.Test;
26  
27  class JdbcTransactionTest {
28    @Test
29    void testSetAutoCommitOnClose() throws Exception {
30      testAutoCommit(true, false, true, false);
31      testAutoCommit(false, false, true, false);
32      testAutoCommit(true, true, true, false);
33      testAutoCommit(false, true, true, false);
34      testAutoCommit(true, false, false, true);
35      testAutoCommit(false, false, false, true);
36      testAutoCommit(true, true, true, true);
37      testAutoCommit(false, true, true, true);
38    }
39  
40    private void testAutoCommit(boolean initialAutoCommit, boolean desiredAutoCommit, boolean resultAutoCommit,
41        boolean skipSetAutoCommitOnClose) throws Exception {
42      TestConnection con = new TestConnection(initialAutoCommit);
43      DataSource ds = mock(DataSource.class);
44      when(ds.getConnection()).thenReturn(con);
45  
46      JdbcTransaction transaction = new JdbcTransaction(ds, TransactionIsolationLevel.NONE, desiredAutoCommit,
47          skipSetAutoCommitOnClose);
48      transaction.getConnection();
49      transaction.commit();
50      transaction.close();
51  
52      assertEquals(resultAutoCommit, con.getAutoCommit());
53    }
54  }