嗯,我现在正在测试遗留代码。而且,我已经接近通过这个测试了,但是它被困在了有评论的线路上。这是片段
new NonStrictExpectations(){
SASCustomerDataAssemblerBD assembleBd;
CustomerTOs tos;
CustomerSASTO to;
Another rowTo;
SelectionJobLogBD logBd;
{
SASCustomerDataAssemblerBD.getInstanceUsingEjbRef(); result = assembleBd;
assembleBd.getData(); result = tos;
..
..
//This line is not being invoked.
//Instead the actual line of code is working. Which is,
//Collections.max(someCollection, someComparator);
//Hence I am stuck because getting null in "to"
invoke(Collections.class, "max", new ArrayList(), new MaxDateComparator()); result = to;
to.getSasDataRow(); result = rowTo;
SelectionJobLogBD.getInstanceUsingEjbRef(); result = logBd;
..
}
};
new TaskSASCustomerReading().execute();
然而,result
的所有值都是模拟的。
最佳答案
用另一种方式解决了:)。模拟了原始方法——仅在底层调用 Collections.max()
的方法。
new MockUp<TaskSASCustomerReading>()
{
@Mock
// This original method is invoking Collections.max().
// Therefore, I just mocked this one, other methods are all original
String findLatestSelectionDate(Collection customerTOs) {
return "";
}
};
new Expectations(){
SASCustomerDataAssemblerBD assembleBd;
CustomerTOs tos;
SelectionJobLogBD logBd;
{
try {
SASCustomerDataAssemblerBD.getInstanceUsingEjbRef(); result = assembleBd;
assembleBd.getData(); result = tos;
SelectionJobLogBD.getInstanceUsingEjbRef(); result = logBd;
}catch(Exception e){}
}
};
new TaskSASCustomerReading().execute();
尽管如此,当我问这个问题时,我一开始就完全误解了这件事。在我原来的问题中,我实际上是在尝试调用一个方法,而不是替换它。 (P.S. 切勿在下类后工作。;))
关于java - 如何替换对被测试类的私有(private)方法的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5322858/