使用Mockito模拟结果集

w1jd8yoj  于 2022-11-08  发布在  其他
关注(0)|答案(3)|浏览(259)

如何模拟结果集?
在测试类中试图模拟如下的resultset但是,在试图测试时得到错误为UnnecessaryStubbingException at语句:

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);
   }
}
ny6fqffe

ny6fqffe1#

为了能够模拟ResultSet,您应该模拟所有允许创建它的对象,即创建PreparedStatementConnection,它本身创建ResultSet。只有在您提供从客户端代码设置连接的方法时,模拟连接才能在测试代码中工作。
这里,作为Connection的conn应该首先作为一个依赖项注入到您的测试装置中:

pstmt = conn.prepareStatement(strQuery.toString());

通常您会建立Connection,例如:

conn = DriverManager.getConnection(DB_URL,USER,PASS);

或者经由X1 M6 N1 X,例如:

conn = ds.getConnection();

所以你应该把这个部分抽象成一个接口或者一个非final类,然后定义一个实现来完成这个处理,这样你就可以模拟创建Connection的部分,这样你就可以模拟整个链:连接准备语句-结果集。
就我个人而言,我会避免这种方式,因为嘲笑太多的事情往往不是正确的选择。
在您的示例中,您需要模拟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));
}

因此,作为替代方案,您可以将之前执行的所有代码移到处理持久性部分的特定类的方法中。这样,您只需要模拟此依赖关系和此方法。您不需要担心连接和任何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));
        }
        .................
    }
   }

当然,DAO组件也必须进行单元测试。
但是,正如前面所说,Assert创建了一个Connection或者它返回了一个PreparedStatement并没有带来任何价值,而测试您的查询是否执行了您期望的功能,在功能覆盖方面要有趣得多。
在这种情况下,您希望针对内存中的DB(如H2)进行测试,因为单元测试不是集成测试,并且单元测试必须快速执行。
要编写DAO/Repository测试,DbunitDbSetup是很好的候选对象,因为它们提供了在每次测试之前设置DB的工具(主要是注入数据和清除数据)。

j0pj023g

j0pj023g2#

这是一个模拟的结果集,我从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");
    }


}
rlcwz9us

rlcwz9us3#

我还希望能够模拟一个具有多行的结果集,并在网上找到了各种答案,但似乎没有一个能满足我的需要。
在我的例子中,我有一个类方法(SUT),它迭代(n)(未知)行,并对它们执行一些逻辑(在生产运行时)。我试图确保从这些行构建的正确对象被返回。在测试时,我知道我要检查的确切行数。
我的解决方案是将 @InjectMocks 插入到我的my 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
}

然后我在我的 setup 方法中添加了一个 @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);
    }

请注意,在上面的代码中,next 有一个额外的 .thenReturn(false),否则它永远不会为false。如果您 while-ing 遍历行,这将导致无限循环。
还要注意,在我的例子中,我的SUT只调用first_name和last_name两次(如上所述,由于行中的其他条件),所以我对它调用了两次 thenReturn(否则将有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行实际上表示两个人的特征。

相关问题