问题描述
我已经开始学习单元测试.我正在使用JUnit 5,我想测试将一些数据插入到数据库中的方法(使用JDBC).这是我的代码:
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());
}
}
它可以正常工作,但实际上是在我的数据库中插入一条记录,但是我想做的是模拟它.是否可以仅使用JUnit来实现?如果没有,我需要什么?一个简单的实现将受到高度赞赏.
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.
编辑
我发现了一个名为 Mockito 的工具,这是我所需要的吗?如果是这样,谁能告诉我如何对我的方法insertTable()进行简单测试?
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()?
推荐答案
这就是我使用模仿工具测试insetTable方法的方法
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());
}
}
这篇关于JUnit 5-JDBC语句测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!