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