如何模拟结果集?
在测试类中,尝试如下模拟结果集,但是,当尝试测试在语句处获得错误为UnnecessaryStubbingException
时:
voObj.setDept(rs.getString(2));
和
voObj.setDeptDesc(rs.getString(3));
关于如何模拟结果集有什么建议吗?
public class Example {
public static void main(String[] s) {
method1();
method2();
..........
}
private Employee method1(String str) {
Connection conn = getConnection();
PreparedStatement pstmt = null;
.........
pstmt = conn.prepareStatement(strQuery.toString());
rs = pstmt.executeQuery();
int ilCounter = 0;
int maxId = method2(loc); //some DB calls here with select
if(null != rs) {
while(rs.next()) {
ilCounter++;
ObjVoBean voObj = new ObjVoBean();
voObj.setLoc(rs.getString(1));
voObj.setDept(rs.getString(2));
voObj.setDeptDesc(rs.getString(3));
}
.................
}
}
private Employee method2(String str1) {
Connection connOHM = getConnection();
PreparedStatement pstmt = null;
.........
//some DB call with select ...
}
}
public class ExampleTest {
@InjectMocks
Example example;
@Mock
private Connection c;
@Mock
private PreparedStatement preStmt;
.....
@Before
public void setUp() {
........
}
@Test
public void testMethod1() throws SQLException {
ResultSet resultSetMock = Mockito.mock(ResultSet.class);
when(resultSetMock.getString(1)).thenReturn("1111");
when(resultSetMock.getString(2)).thenReturn("2222");
when(resultSetMock.getString(3)).thenReturn("dept desc");
when(c.prepareStatement(any(String.class))).thenReturn(preStmt);
when(resultSetMock.next()).thenReturn(true).thenReturn(false);
doReturn(resultSetMock).when(preStmt).executeQuery();
example.method1("1111");
assertTrue(true);
}
}
为了能够模拟ResultSet
,您应该模拟所有允许创建它的对象,即创建PreparedStatement
的Connection
,它本身创建ResultSet
。只有当您提供了一种从客户端代码设置连接的方法时,模拟连接才能在测试代码中工作。
这里conn
,也就是连接,应该首先作为依赖项注入到测试夹具中:
pstmt = conn.prepareStatement(strQuery.toString());
通常,您创建一个Connection
,例如:
conn = DriverManager.getConnection(DB_URL,USER,PASS);
或者经由CCD_ 8例如
conn = ds.getConnection();
因此,您应该将这一部分抽象为一个接口或一个非最终类,并定义一个执行此处理的实现。通过这种方式,您可以模拟创建Connection的部分。因此,您可以模拟整个链:Connection PreparedStatement ResultSet。
就我个人而言,我会避免这种方式,因为嘲笑太多事情往往不是正确的选择
在您的情况下,您需要模拟ResultSet来测试加载ResultSet:后的后处理
while(rs.next()) {
ilCounter++;
ObjVoBean voObj = new ObjVoBean();
voObj.setLoc(rs.getString(1));
voObj.setDept(rs.getString(2));
voObj.setDeptDesc(rs.getString(3));
}
因此,作为替代方案,您可以在处理持久性部分的特定类的方法中移动之前执行的所有代码。通过这种方式,您只需要模拟这个依赖项和这个方法。您不需要担心Connection和任何JDBC细节。
EmployeeDAO employeeDAO; // dependency to mock
// constructor with dependency
public Example(EmployeeDAO employeeDAO){
this.employeeDAO = employeeDAO;
}
private Employee method1(String str) {
ResultSet resultSet = employeeDAO.load(str);
if(null != rs) {
while(rs.next()) {
ilCounter++;
ObjVoBean voObj = new ObjVoBean();
voObj.setLoc(rs.getString(1));
voObj.setDept(rs.getString(2));
voObj.setDeptDesc(rs.getString(3));
}
.................
}
}
在couse中,DAO组件也必须进行统一测试
Bu,如前所述,断言创建了Connection
或它返回了PreparedStatement
并没有带来价值。而测试您的查询是否执行您对它们的期望,在功能覆盖方面要有趣得多
在这种情况下,您希望针对内存中的DB(如H2)进行测试,因为单元测试不是集成测试,并且单元测试必须快速执行
要编写DAO/Repository测试,Dbunit和DbSetup是很好的候选者,因为它们提供了在每次测试之前设置DB的工具(主要是注入数据和清除数据)。
这是我从GitHub 中剽窃的模拟结果集
/*
* Distributed under the terms of the MIT License.
* Copyright (c) 2009, Marcelo Criscuolo.
*/
package commondb.mock;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.apache.commons.lang.StringUtils;
public class MockResultSet implements ResultSet {
static final String INVALID_COLUMN_NAME = "invalid column name";
static final String INVALID_COLUMN_INDEX = "invalid column index";
static final DateFormat DATE_ISO_8601 = new SimpleDateFormat("yyyy-MM-dd");
private List<String[]> rowset = new ArrayList<String[]>();
private int cursor = -1;
private Map<String, Integer> columnMap = new HashMap<String, Integer>();
private CSVLineSplitter splitter = new CSVLineSplitter();
public MockResultSet() {
}
/**
* ResultSet rs = new MockResultSet(
* "ID,NAME,CITY",
* "3,John,New York",
* "4,Bill,Sydney"
* );
*
* @param str headers and rows that form the CSV data
*/
public MockResultSet(String... str) throws SQLException {
loadCSV(new StringReader(StringUtils.join(str, "n")));
}
/**
* @param in source from where the CSV data will be read
*
* @throws SQLException any exception will be wrapped
* on SQLException, so that it is not necessary to
* add additional catches to client code.
*/
public MockResultSet(Readable in) throws SQLException {
loadCSV(in);
}
public void loadCSV(Readable in) throws SQLException {
final Scanner sc = new Scanner(in);
if (!sc.hasNextLine()) {
sc.close();
throw new SQLException("empty data source");
}
// load column headers
String line = sc.nextLine();
int index = 1;
for (String column : splitter.split(line)) {
columnMap.put(column, index);
index++;
}
// load data
while (sc.hasNextLine()) {
line = sc.nextLine();
String[] row = splitter.split(line);
rowset.add(row);
}
sc.close();
}
@Override
public boolean absolute(int row) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void afterLast() throws SQLException {
cursor = rowset.size();
}
@Override
public void beforeFirst() throws SQLException {
cursor = -1;
}
@Override
public void cancelRowUpdates() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void clearWarnings() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void close() throws SQLException {
// noop
}
@Override
public void deleteRow() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public int findColumn(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean first() throws SQLException {
if (rowset.size() > 0) {
cursor = 0;
return true;
}
return false;
}
@Override
public Array getArray(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Array getArray(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public InputStream getAsciiStream(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public InputStream getAsciiStream(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public BigDecimal getBigDecimal(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
@Deprecated
public BigDecimal getBigDecimal(int columnIndex, int scale)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
@Deprecated
public BigDecimal getBigDecimal(String columnLabel, int scale)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public InputStream getBinaryStream(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public InputStream getBinaryStream(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Blob getBlob(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Blob getBlob(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean getBoolean(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean getBoolean(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public byte getByte(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public byte getByte(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public byte[] getBytes(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public byte[] getBytes(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Reader getCharacterStream(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Reader getCharacterStream(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Clob getClob(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Clob getClob(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public int getConcurrency() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public String getCursorName() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
/**
* Dates are expected to be formatted as yyyy-MM-dd.
* See http://en.wikipedia.org/wiki/ISO_8601#Calendar_dates
*/
public Date getDate(int columnIndex) throws SQLException {
try {
String value = getValue(columnIndex);
Date date = null;
if ( (value != null) && (value.trim().length() >= 0)) {
date = new Date(DATE_ISO_8601.parse(value).getTime());
}
return date;
} catch (Exception e) {
throw new SQLException(e);
}
}
@Override
public Date getDate(String columnLabel) throws SQLException {
return getDate(getColumnIndex(columnLabel));
}
@Override
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Date getDate(String columnLabel, Calendar cal) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public double getDouble(int columnIndex) throws SQLException {
try {
String value = getValue(columnIndex);
if ( (value == null) || (value.trim().length() == 0)) {
value = "0";
}
value = value.replace(',', '.');
return Double.parseDouble(value);
} catch (Exception e) {
throw new SQLException(e);
}
}
@Override
public double getDouble(String columnLabel) throws SQLException {
return getDouble(getColumnIndex(columnLabel));
}
@Override
public int getFetchDirection() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public int getFetchSize() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public float getFloat(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public float getFloat(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public int getHoldability() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public int getInt(int columnIndex) throws SQLException {
try {
String value = getValue(columnIndex);
if ( (value == null) || (value.trim().length() == 0)) {
value = "0";
}
return Integer.parseInt(value);
} catch (Exception e) {
throw new SQLException(e);
}
}
@Override
public int getInt(String columnLabel) throws SQLException {
return getInt(getColumnIndex(columnLabel));
}
@Override
public long getLong(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public long getLong(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Reader getNCharacterStream(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Reader getNCharacterStream(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public NClob getNClob(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public NClob getNClob(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public String getNString(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public String getNString(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Object getObject(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Object getObject(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Object getObject(int columnIndex, Map<String, Class<?>> map)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Object getObject(String columnLabel, Map<String, Class<?>> map)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public <T> T getObject(String columnLabel, Class<T> type) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Ref getRef(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Ref getRef(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public int getRow() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public RowId getRowId(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public RowId getRowId(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public SQLXML getSQLXML(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public SQLXML getSQLXML(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public short getShort(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public short getShort(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Statement getStatement() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public String getString(int columnIndex) throws SQLException {
return getValue(columnIndex);
}
private String getValue(int columnIndex) throws SQLException {
if ( (cursor < 0) || (cursor >= rowset.size()) ) {
throw new SQLException("cursor not pointing to a valid row");
}
String[] row = rowset.get(cursor);
if ( (columnIndex < 0) || (columnIndex > row.length) ) {
throw new SQLException(INVALID_COLUMN_INDEX);
}
return row[columnIndex - 1];
}
@Override
public String getString(String columnLabel) throws SQLException {
return getString(getColumnIndex(columnLabel));
}
private Integer getColumnIndex(String columnLabel) throws SQLException {
Integer index = columnMap.get(columnLabel);
if (index == null) {
throw new SQLException(INVALID_COLUMN_NAME);
}
return index;
}
@Override
public Time getTime(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Time getTime(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Time getTime(int columnIndex, Calendar cal) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Time getTime(String columnLabel, Calendar cal) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Timestamp getTimestamp(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Timestamp getTimestamp(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Timestamp getTimestamp(int columnIndex, Calendar cal)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public Timestamp getTimestamp(String columnLabel, Calendar cal)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public int getType() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public URL getURL(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public URL getURL(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
@Deprecated
public InputStream getUnicodeStream(int columnIndex) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
@Deprecated
public InputStream getUnicodeStream(String columnLabel) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public SQLWarning getWarnings() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void insertRow() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean isAfterLast() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean isBeforeFirst() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean isClosed() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean isFirst() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean isLast() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean last() throws SQLException {
if (rowset.size() > 0) {
cursor = rowset.size() - 1;
return true;
}
return false;
}
@Override
public void moveToCurrentRow() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void moveToInsertRow() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean next() throws SQLException {
final boolean hasNext = (cursor + 1) < rowset.size();
if (hasNext) {
cursor++;
}
return hasNext;
}
@Override
public boolean previous() throws SQLException {
cursor--;
if (cursor < -1) {
cursor = -1; // one row before the first is the limit
}
final boolean beforeFirst = (cursor < 0);
return !beforeFirst;
}
@Override
public void refreshRow() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean relative(int rows) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean rowDeleted() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean rowInserted() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public boolean rowUpdated() throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void setFetchDirection(int direction) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void setFetchSize(int rows) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateArray(String columnLabel, Array x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, int length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, int length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, long length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, long length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBigDecimal(int columnIndex, BigDecimal x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBigDecimal(String columnLabel, BigDecimal x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, int length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x, int length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, long length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x,
long length) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBlob(int columnIndex, Blob x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBlob(String columnLabel, Blob x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream, long length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream,
long length) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBoolean(int columnIndex, boolean x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBoolean(String columnLabel, boolean x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateByte(int columnIndex, byte x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateByte(String columnLabel, byte x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBytes(int columnIndex, byte[] x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateBytes(String columnLabel, byte[] x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateCharacterStream(int columnIndex, Reader x)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, int length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader,
int length) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, long length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader,
long length) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateClob(String columnLabel, Clob x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateClob(int columnIndex, Reader reader) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateClob(String columnLabel, Reader reader)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateClob(int columnIndex, Reader reader, long length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateClob(String columnLabel, Reader reader, long length)
throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateDate(int columnIndex, Date x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateDate(String columnLabel, Date x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateDouble(int columnIndex, double x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
@Override
public void updateDouble(String columnLabel, double x) throws SQLException {
throw new UnsupportedOperationException("to be implemented");
}
}
我还希望能够模拟具有多行的ResultSet,并在网上找到了各种答案,但似乎都不能满足我的需求。
在我的例子中,我有一个类方法(SUT),它迭代(n)(未知)行数,并对它们执行一些逻辑(在生产运行时)。我正在努力确保返回从这些行构建的正确对象。在测试时,我知道要检查的确切行数。
我的解决方案是@InjectMocks到我的repo类中;工厂;通过repo构造函数提供连接的连接类。这就是我所做的:
import static org.mockito.Mockito.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.SomeStuff.MyRepository;
import com.SomeStuff.MyConnectionFactory;
import com.SomeStuff.Widget;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
public class MyClass {
@InjectMocks
private MyRepository myRepository;
@Mock
private MyConnectionFactory mcf;
@Mock
private Connection c;
@Mock
private PreparedStatement stmt;
@Mock
private ResultSet rs;
// snipped code below, more to follow
}
然后我在我的设置方法中添加了@BeforeEeach,里面有秘密酱汁。在我的例子中,我知道SUT中的代码想要迭代9个伪行,我也知道在少数情况下,如果两行满足某些特性,它只需要使用两行。
public class MyClass {
// snipped the previous stuff above
MockitoAnnotations.openMocks(this);
when(mcf.getConnection()).thenReturn(c);
when(c.prepareStatement(any(String.class))).thenReturn(stmt);
when(rs.next())
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true)
.thenReturn(false);
when(rs.getInt("person_id"))
.thenReturn(10001)
.thenReturn(10001)
.thenReturn(10001)
.thenReturn(10001)
.thenReturn(10001)
.thenReturn(10002)
.thenReturn(10002)
.thenReturn(10002)
.thenReturn(10002);
when(rs.getString("first_name"))
.thenReturn("John")
.thenReturn("Dave");
when(rs.getString("last_name"))
.thenReturn("Doe")
.thenReturn("Smith");
when(rs.getString("key_value"))
.thenReturn("Yes")
.thenReturn("")
.thenReturn("8005551212")
.thenReturn("Hello,")
.thenReturn("No")
.thenReturn("")
.thenReturn("")
.thenReturn("World!")
.thenReturn("No");
when(stmt.executeQuery()).thenReturn(rs);
}
请注意,在上面的代码中还有一个额外的。然后为返回(false)下一个,否则它永远不会是false。如果在行中执行时,这将导致中缀循环。
还要注意的是,在我的情况下,我的SUT只调用first_name和last_name两次(如上所述,由于行中的其他条件),所以我在它上调用然后返回两次(否则会有8次调用,这不适合我的需要。
最后我这样测试它:
public class MyClass {
// Everything snipped above
@Test
@SneakyThrows
public void getPeople_correct_number_of_Person_is_retrieved() {
List<Person> people = myRepository.getPeople();
assertEquals(1, people.size());
}
}
在我上面的例子中,我希望返回一个Person,其中9行实际上代表了两个人的特征。