我在为带有While循环的方法编写JUnit测试时遇到了一些困难。我的方法如下所示:
private void deleteMethod(DeleteRequest dr){
// below statement am calling some service which returns me a object after querying it from Database.
SomeObject ob = db.getdata(dr);
while(ob != null) {
// this method deletes the Data from DB
db.deleteData(ob);
// again calling the same service operation as we did before while loop. I have a situation where my service only returns single record at a time. It is avoidable that I need to do a dirty job.
ob = db.getdata(dr);
}
以下是我的JUnit:
@Test
public void testDeleteMethod() throws Exception{
DeleteRequest mockDR = new DeleteRequest();
mockDR.setX(y);
SomeObject mockOB = new SomeObject();
mockOB.setZ(k);
// making a mockcall to the method before I can assert anything
mockClassObject.deleteMethod(mockDR);
}
上面的JUnit方法在执行中受到了冲击,我明白它不会脱离while循环。我如何处理这个问题。只是提到使用Mockito框架,我不知道在Mockito中是否有任何方法可以处理这种情况。
答案 0 :(得分:3)
使用Mockito,您必须先模拟数据库连接,然后在测试方法之前使用@InjectMocks,构造函数注入或通过setter将其注入服务。这就是我写测试的方式。
@Test
public void testDeleteMethod() throws Exception{
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.setX(y);
SomeObject someObject = new SomeObject();
someObject.setZ(k);
Database db = Mockito.mock(Database.class);
// Notice chain of calls
Mockito.when(db.getdata(deleteRequest))
.thenReturn(someObject).thenReturn(null);
// TODO Inject the Database object into your mockClassObject.
// making a mock call to the method before I can assert anything
mockClassObject.deleteMethod(deleteRequest);
Mockito.verify(db, Mockito.times(2)).getdata(deleteRequest);
Mockito.verify(db).deleteData(someObject);
}
您可以看到我将db.getData()
方法上的调用链接两次,第一次返回someObject
,第二次返回null
。