How do you test code that uses PreparedStatement?

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(); } }

PreparedStatement Java JUnit Mockito Unit Testing Database Testing