简体   繁体   中英

JUnit 5 - JDBC statements testing

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

You can use the DbUnit framework with an H2 or HSQL Memory Database.

You will open real connections to a memory Database and you could check that the records is saved by using DataSets

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

    }    
}

So If using PowerMockito with version 1.6.5 I would test your code as following

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Datasource.class, DriverManager.class, Connection.class })
public class DatasourceTest {

    @Mock
    Connection con;

    @Mock
    PreparedStatement ps;

    @Test
    public void insertTableTest() throws Exception {

        PowerMockito.mockStatic(DriverManager.class);
        PowerMockito.when(DriverManager.getConnection(
                Mockito.eq("jdbc:mysql://127.0.0.1:3306/java"),
                Mockito.eq("root"),
                Mockito.eq(""))).thenReturn(con);

        Datasource ds = Mockito.mock(Datasource.class);
        PowerMockito.doCallRealMethod().when(ds).open();
        PowerMockito.doCallRealMethod().when(ds).insertTable();

        boolean result = ds.open();
        Assert.assertTrue(result);

        Mockito.when(con.prepareStatement(Mockito.eq("INSERT INTO artists(name) VALUES(?)"))).thenReturn(ps);
        Mockito.when(ps.executeUpdate()).thenReturn(1);

        result = ds.insertTable();
        Assert.assertTrue(result);

        Mockito.verify(ps).setString(Mockito.eq(1), Mockito.eq("Test"));
        Mockito.verify(ps).executeUpdate();
        Mockito.verify(con).prepareStatement(Mockito.eq("INSERT INTO artists(name) VALUES(?)"));

    }
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM