【问题标题】:How to Replace The Call to A Private Method of The Class Being Tested如何替换对被测试类的私有方法的调用
【发布时间】:2011-07-16 10:09:44
【问题描述】:

嗯,我现在正在测试遗留代码。而且,我在某个地方附近可以通过这个测试,但它卡在上面有 cmets 的线上。这是sn-p

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

【问题讨论】:

  • to 是否在其他地方被实例化?
  • @Feanor:它是一个模型实例。
  • 澄清一下,“模型实例”是指在此 NonStrictExpectations 记录阶段有另一个调用,其中结果分配给 to?
  • @Feanor:不不,我刚刚更新了代码以显示to

标签: java unit-testing junit mocking jmockit


【解决方案1】:

以另一种方式解决了它:)。模拟了原始方法——只有在底层调用 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. 千万不要在下班后工作。;)

【讨论】:

    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多