我试图用不同的条件测试方法次数。条件取决于从测试方法内部调用的方法返回的值。但是我一次又一次地收到同样的结果。
@Test
public void testMethod() {
try {
TestBn testBn = getTestBn();
when(mockDatabase.getDBConnection()).thenReturn(conn);
PowerMockito.doNothing().when(mockDatabase).closeDBConnection();
List<String> accListForCurrentYear = new ArrayList<>();
accListForCurrentYear.add("Test String 1");
accListForCurrentYear.add("Test String 2");
accListForCurrentYear.add("Test String 3");
accListForCurrentYear.add("Test String 4");
for (String accStr : accListForCurrentYear)
{
AccountTypeBn acctypeDto = new AccountTypeBn();
acctypeDto.setAccountTypes(accStr);
when(mockOnlineClaimDAO.getAccountType(Mockito.any(Connection.class), Mockito.anyString(),
Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Date.class),
Mockito.any(Date.class))).thenReturn(acctypeDto);
UserDetailsBn usrDtlsBn = getCommonUserDetails();
TestBn newTestBn = mockClaimBO.validateInitialClaimDtls(usrDtlsBn, TestBn); //Method to be tested
for (ResultBn resultBn : newTestBn.getAccbnList())
{
System.out.println("Property1 : "+resultBn.getProperty1());
System.out.println("Property2 : "+resultBn.getProperty2());
System.out.println("Property3 : "+resultBn.getProperty3());
System.out.println("Property4 : "+resultBn.getProperty4());
System.out.println("-----------------------------------");
}
}
} catch (Exception e) {
fail("### testMethod ### Failed with following error: " + getStackTrace(e));
}
}
我收到相同的输出(第一次迭代后存储的属性)。
答案 0 :(得分:1)
我认为你的函数mockOnlineClaimDAO.getAccountType
总是返回相同的对象。
最佳解决方案是使用eq
为mockOnlineClaimDAO.getAccountType
函数定义一个唯一的匹配器,因为现在只使用通配符匹配器。示例:
when(mockOnlineClaimDAO.getAccountType(Mockito.any(Connection.class), Mockito.eq(accStr),...`
您拥有的另一个选择是使用连续的存根。然后,您必须添加多个thenReturn
语句:
when(mockOnlineClaimDAO.getAccountType(Mockito.any(Connection.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Date.class), Mockito.any(Date.class)))
.thenReturn(new AccountTypeBn("Test String 1"))
.thenReturn(new AccountTypeBn("Test String 2"))
.thenReturn(new AccountTypeBn("Test String 3"))
.thenReturn(new AccountTypeBn("Test String 4"));
或者传递1 thenReturn
块中的所有返回值:
when(mockOnlineClaimDAO.getAccountType(Mockito.any(Connection.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Date.class), Mockito.any(Date.class)))
.thenReturn(new AccountTypeBn("Test String 1"), new AccountTypeBn("Test String 2"), new AccountTypeBn("Test String 3"));
每次调用stubbed函数时,都会返回下一个对象。