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    *       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.logging.jdbc;
17  
18  import static org.mockito.ArgumentMatchers.anyString;
19  import static org.mockito.ArgumentMatchers.contains;
20  import static org.mockito.Mockito.times;
21  import static org.mockito.Mockito.verify;
22  import static org.mockito.Mockito.when;
23  
24  import java.sql.SQLException;
25  import java.sql.Statement;
26  
27  import org.apache.ibatis.logging.Log;
28  import org.junit.jupiter.api.Assertions;
29  import org.junit.jupiter.api.BeforeEach;
30  import org.junit.jupiter.api.Test;
31  import org.junit.jupiter.api.extension.ExtendWith;
32  import org.mockito.Mock;
33  import org.mockito.junit.jupiter.MockitoExtension;
34  
35  @ExtendWith(MockitoExtension.class)
36  class StatementLoggerTest {
37  
38    @Mock
39    Statement statement;
40  
41    @Mock
42    Log log;
43  
44    private Statement st;
45  
46    @BeforeEach
47    void setUp() throws SQLException {
48      st = StatementLogger.newInstance(statement, log, 1);
49    }
50  
51    @Test
52    void shouldPrintLog() throws SQLException {
53      when(log.isDebugEnabled()).thenReturn(true);
54      st.executeQuery("select 1");
55  
56      verify(log).debug(contains("Executing: select 1"));
57    }
58  
59    @Test
60    void shouldPrintLogForUpdate() throws SQLException {
61      when(log.isDebugEnabled()).thenReturn(true);
62      when(statement.execute(anyString())).thenReturn(true);
63      String sql = "update name = '' from test";
64      boolean execute = st.execute(sql);
65  
66      verify(log).debug(contains(sql));
67      Assertions.assertTrue(execute);
68    }
69  
70    @Test
71    void shouldNotPrintLog() throws SQLException {
72      st.getResultSet();
73      st.close();
74      verify(log, times(0)).debug(anyString());
75    }
76  }