0

I'm trying to mock a private method using JMockit, and struggling. I have been working through the tutorials and can mock private methods that return values nut not without. This particular method interacts with a database and does not return anything. For the purposes of this test all I want to do is effectively mask this method out. The test format I am using is shown below, note that usually the result would be straight after the method deencapsulation is invoked.

    @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.....
}
John Paul
  • 772
  • 1
  • 6
  • 17
  • Since it is a private method, can you not just change the signature of method to return some value. In this case, if the database operation is successful, return 0 else return 1. It's kind of hard to think of any private method which does not convey the result of it's activity to calling method. It can be either by return value or throwing exception. – Gaurav Dec 05 '14 at 16:58

1 Answers1

1

Which abstraction are you using to interact with the database?

I'd recommend mocking this rather than trying to mock something that from your test's point of view should not exist.

Mocking a private method means that you're effectively leaving code in your application uncovered by tests.

darrengorman
  • 12,952
  • 2
  • 23
  • 24
  • Thanks for you're input [rol.retrieveAndSaveReport("","",1) interacts with the database]. I got pulled off this when I was first working on it and now I come back to it I can think of better ways round my problem. The simplest was to use System-rules api. That has method ExpectedSystemExit() and expectSystemExitWithStatus(int). The only catch for anyone wanting to use this is that they will need to get the correct JUnit version to use with it. – John Paul Oct 23 '15 at 13:41