我有一个导致异常的类。我想嘲笑这个例外,但有了覆盖范围(所以需要间谍),我该如何嘲笑mockito,以便Junit覆盖范围能够将这些例外算作覆盖范围?
例如:
private List<Data> _getSomeData(Key key) {
log.debug(logPrefix + " GetSomeData");
Connection dbc = null;
PreparedStatement st = null;
ResultSet rs = null;
String q = null;
....
try {
dbc = DataSourceUtils.getConnection(dataSource);
dbc.setAutoCommit(false);
q = "SELECT value FROM table where x = ? and y = ? and z = ?";
st = dbc.prepareStatement(q);
int ix = 1;
st.setInt(ix++, key.x);
st.setInt(ix++, key.y);
st.setInt(ix++, key.z);
rs = st.executeQuery();
while (rs.next()) {
Data data=new Data();
key.id = rs.getLong("x");
key.y = y;
....
DataList.add(data);
}
} catch (Exception e) {
throw new DbException(e, q);
} finally {
DbUtil.cleanup(log, rs, st, dbc);
}
return dataList;
}
因此,从上面来看,我想要的是涵盖例外情况。我该如何覆盖它?
Jutest->
@Test
public void testException(){
// DataImpl dataDao = new DataImpl();
// dataDao.setLog(new LogImpl());
DataImpl dataDao = Mockito.spy(new DataImpl());
Key key= new Key();
key.x = 1;
key.y = 1;
key.z = 1;
String q =
" SELECT data.* n" +
" FROM SOME_DATA d1n" +
" WHEREn "+
" d1.x = ? n " +
" AND ROUND (d1.y/ 1000 - 1) = ? n" +
" AND MOD (d1.z, 1000) = ?";
Mockito.doThrow(new DbException(null, q)).when(invPPNDataDao)._getSomeData(Key);
}
以上内容将起作用,但不包括在内。
这里需要做的是依赖项注入。然后你可以模拟它并定义它的行为。目前,您正在方法中构造许多对象(DataSourceUtils.getConnection(dataSource)
、new Data()
…),这些对象很难测试。
您可以创建类DbcProvider
:
public class DbcProvider {
public Connection newDbc() {
DataSourceUtils.getConnection(dataSource);
}
}
然后在测试中模拟DbcProvider
,并将其设置为在调用newDbc
时抛出异常,然后调用方法_getSomeData
。