I've begun learning unit tests. I'm working with JUnit 5 and I'd like to test my method that inserts some data into my database (using JDBC). Here's my code:
Datasource.java
import java.sql.*;
public class Datasource {
public static final String CONNECTION = "jdbc:mysql://127.0.0.1:3306/java";
private Connection connection;
public boolean open() {
try {
connection = DriverManager.getConnection(CONNECTION, "root", "");
return true;
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
public boolean insertTable() {
try {
String query = "INSERT INTO artists(name) VALUES(?)";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, "Test");
int result = stmt.executeUpdate();
if (result == 1) return true;
return false;
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
}
DatasourceTest.java
import static org.junit.jupiter.api.Assertions.*;
class DatasourceTest {
private Datasource datasource;
@org.junit.jupiter.api.BeforeEach
void setUp() {
datasource = new Datasource();
if (!datasource.open()) {
System.exit(-1);
}
}
@org.junit.jupiter.api.Test
void insertTable() {
assertTrue(datasource.insertTable());
}
}
It works fine but it actually inserts a record into my database, but I what I want to do is to simulate it. Is it possible to achieve that using only JUnit? If not, what do I need? And a simple implementation would be highly appreciated.
EDIT
I found out about a tool called Mockito, is it what I need? If so, could anyone show me how to deploy a simple test of my method insertTable()?
解决方案
This is what I did using mockito to test insetTable method
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DatasourceTest {
@InjectMocks
Datasource datasource;
@Mock
Connection connection;
@Mock
PreparedStatement stmt;
@Before
public void setUp() throws SQLException {
when(connection.prepareStatement(eq("INSERT INTO artists(name) VALUES(?)"))).thenReturn(stmt);
when(stmt.executeUpdate()).thenReturn(1);
}
@Test
public void testInsertTable() {
assertTrue(datasource.insertTable());
}
}