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);
}
}
如何使用Junit测试在java中测试此方法
答案 0 :(得分:0)
以下是我们如何使用JUnit和Mockito测试此功能的示例:
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());
}
}
}