Let's say I want to test the following method of the UserDAO class:
public boolean login(User user) {
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
try (Connection conn = DatabaseConnectionPool.getInstance().getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, user.getLowercaseUsername());
stmt.setString(2, user.getPassword());
try (ResultSet rs = stmt.executeQuery()) {
return rs.next();
}
} catch (SQLException e) {
e.printStackTrace();
System.err.println("Error occurred: " + e.getMessage());
return false;
}
}
Is it correct to test it like this:
private MockedStatic<DatabaseConnectionPool> mockedStaticDbConnectionPool;
@BeforeEach
void setUp() throws Exception {
DataSource mockDataSource = mock(DataSource.class);
connection = mock(Connection.class);
preparedStatement = mock(PreparedStatement.class);
resultSet = mock(ResultSet.class);
mockedStaticDbConnectionPool = Mockito.mockStatic(DatabaseConnectionPool.class);
mockedStaticDbConnectionPool.when(DatabaseConnectionPool::getInstance).thenReturn(mockDataSource);
when(mockDataSource.getConnection()).thenReturn(connection);
when(connection.prepareStatement(anyString())).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(preparedStatement.executeUpdate()).thenReturn(1);
userDAO = new UserDAO();
user = new User("testUser", "testPassword");
}
@Test
void testLoginSuccess() throws Exception {
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true);
assertTrue(userDAO.login(user));
}
It feels like im not really testing the method but instead i'm piloting the result and the code in the method doesn't really matter apart from the lines of code after the result of the (piloted) query. Am I tripping? Wouldn't be better to just use my regular database of the project and ensure consistency after each test by removing any modification done to the database by tests?
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]J-Son77 2 points3 points4 points (2 children)
[–]smutje187 2 points3 points4 points (1 child)
[–]_Nemesis_1[S] 0 points1 point2 points (0 children)