Can you help me understand this piece of code?
I am trying to verify that database connection is closed. Even if Mocikto verifies that close() method were called connection is not closed.
Code I am testing (it uses inside con.close()):
public static void closeConnection(CallableStatement cs, Connection conn) {
JdbcUtils.closeStatement(cs);
JdbcUtils.closeConnection(conn);
}
And test:
public class DataProviderTest {
@InjectMocks
DataProvider dataProvider;
@Mock
OracleConnection oracleConnection;
@Mock
DatabaseMetaData databaseMetadata;
@Mock
PoolDataSource dataSource;
@Mock
OracleCallableStatement oracleCallableStatement;
@BeforeEach
public void setUp() throws SQLException {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(dataProvider, "parseSQLErrorFuntion", "Some SQL error function");
Mockito.when(dataSource.getConnection()).thenReturn(oracleConnection);
Mockito.when(oracleConnection.getMetaData()).thenReturn(databaseMetadata);
Mockito.when(oracleConnection.prepareCall(Mockito.anyString())).thenReturn(oracleCallableStatement);
}
@Test
public void closeConnectionTest() throws SQLException {
OracleConnection connection = dataProvider.getConnection();
OracleCallableStatement statement = oracleCallableStatement;
assertFalse(connection.isClosed());
dataProvider.closeConnection(statement, connection);
Mockito.verify(connection, Mockito.atLeast(1)).close(); //pass
Mockito.verify(statement, Mockito.atLeast(1)).close(); //pass
assertTrue(connection.isClosed()); // expected: <true> but was: <false>
}
}
The connection in your test is a mocked object, therefor running the close method does not actually change the value of isClosed from false to true.
You can remove the last assert, since it's a mock, all you need to verify is that the close method was executed on the connection, you don't need to verify what it did.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加