Testing code that uses PreparedStatement
in Java is essential for ensuring that your database interactions are safe and efficient. Utilizing unit testing frameworks like JUnit along with mocking libraries such as Mockito can help you achieve this. The approach typically involves simulating the behavior of the database and verifying that your code interacts with it in the expected manner.
Here is an example of testing a method that uses PreparedStatement
:
import static org.mockito.Mockito.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
public class UserRepositoryTest {
@Test
public void testAddUser() throws SQLException {
// Arrange
Connection mockConnection = mock(Connection.class);
PreparedStatement mockStatement = mock(PreparedStatement.class);
when(mockConnection.prepareStatement(any(String.class))).thenReturn(mockStatement);
UserRepository userRepository = new UserRepository(mockConnection);
User user = new User("John", "Doe");
// Act
userRepository.addUser(user);
// Assert
ArgumentCaptor sqlCaptor = ArgumentCaptor.forClass(String.class);
verify(mockConnection).prepareStatement(sqlCaptor.capture());
String preparedSQL = sqlCaptor.getValue();
assertEquals("INSERT INTO users (first_name, last_name) VALUES (?, ?)", preparedSQL);
verify(mockStatement).setString(1, "John");
verify(mockStatement).setString(2, "Doe");
verify(mockStatement).executeUpdate();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?