2014-12-05 58 views
0

我试图嘲笑使用JMockit的私人方法,并挣扎。我一直在研究这些教程,可以模拟那些返回值不是没有的值的私有方法。这种特殊的方法与数据库交互,不会返回任何东西。为了这个测试的目的,我想要做的就是有效地屏蔽掉这个方法。我正在使用的测试格式如下所示,请注意,通常在调用方法解封装后结果将是直接的。JMockit,我如何嘲笑没有回报的私人方法

@Test 
public void testRetrieveAndSaveReport() { 

    //Make class with private class final, to be used in the Exceptionsinners class 
    final ESReportOutputLogic eSReportOutputLogic = new ESReportOutputLogic(); 

    // Define Expectations 
    // pass eSReportOutputLogic as argument to make it a Mocked type in the Exceptions Class 
    new Expectations(eSReportOutputLogic){ 
     ESReportOutputLogic eSReportOutputLogic; 
     { 
      Deepcapsulation.invoke(eSReportOutputLogic); 

     } 
    }; 

    ESReportOutputLogic rol = new ESReportOutputLogic(); 
    rol.retrieveAndSaveReport("","",1); 

    // asserts..... 
} 
+0

由于它是一个私有方法,你不能只是改变方法的签名来返回一些值。在这种情况下,如果数据库操作成功,则返回0,否则返回1.很难想象任何不将其活动结果传递给调用方法的私有方法。它可以通过返回值或抛出异常。 – Gaurav 2014-12-05 16:58:52

回答

1

您使用哪种抽象方式与数据库交互?

我建议嘲笑这个,而不是试图嘲笑从你的测试的角度来看should not exist

嘲讽私有方法意味着您实际上将代码留在您的应用程序中,并且未被测试覆盖。

+0

感谢您的输入[rol.retrieveAndSaveReport(“”,“”,1)与数据库交互]。当我第一次研究这个问题时,我得到了这个,现在我回到它,我可以想出更好的方法来解决我的问题。最简单的就是使用System-rules API。这有方法ExpectedSystemExit()和expectSystemExitWithStatus(int)。任何想要使用它的人都会得到正确的JUnit版本才能使用它。 – 2015-10-23 13:41:18