简体   繁体   中英

how do i test this method in java using JunitTest

 public int getRewardId() {

    query = "SELECT max(rewardId) as rewardId FROM rewards";
    ResultSet rs = null;
    int check = 0;
    try
    {
        rs = st.executeQuery(query);
        while (rs.next()) {
            check = rs.getInt("rewardId") + 1;
        }
    }
    catch(SQLException e)
    {
        JOptionPane.showMessageDialog(null,e.getMessage(),"SQL Error",
            JOptionPane.INFORMATION_MESSAGE);
    }
}

how do i test this method in java using Junit test

Here's an example of how we can use JUnit and Mockito to test this functionality:

import junit.framework.TestCase;
import org.junit.Test;
import javax.swing.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class YourClass {

    PreparedStatement st;

    public YourClass(PreparedStatement st) {
        this.st = st;
    }

    public int getRewardId() {

        String query = "SELECT max(rewardId) as rewardId FROM rewards";
        ResultSet rs = null;
        int check = 0;
        try {
            rs = st.executeQuery(query);
            if (rs.next()) {
                check = rs.getInt("rewardId") + 1;
            }
        } catch(SQLException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "SQL Error",
                                          JOptionPane.INFORMATION_MESSAGE);
        }
        return check;
    }

    public static class YourClassTest extends TestCase {    

        @Test
        public void testGetRewardId() throws SQLException {
            PreparedStatement st = mock(PreparedStatement.class);
            YourClass yourClass = new YourClass(st);

            ResultSet rs = mock(ResultSet.class);
            when(rs.next()).thenReturn(true).thenReturn(false);
            when(rs.getInt(any())).thenReturn(2);

            when(st.executeQuery(anyString())).thenReturn(rs);

            assertEquals(3, yourClass.getRewardId());
        }
    }
}

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