junit mysql脚本,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());

}

}

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值