如何取代被测试类私有方法的调用

时间:2011-03-16 08:48:39

标签: java unit-testing junit mocking jmockit

好吧,我现在正在测试遗留代码。而且,我差不多通过了这个测试,但它仍然坚持对它进行评论。这是片段

    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的所有值都被模拟了。

1 个答案:

答案 0 :(得分:2)

以另一种方式解决了它:)。嘲笑原始方法 - 只有在引擎盖下调用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。下班后不要工作。;)