Search code examples
unit-testingprivatejmockit

Verification of private method in JMockit


I want to verify that a private method has been called in my JMockit test class. I don't want to mock the private method, only make sure it has been called.

Is this possible, and if so how?

(I found a similar question but there the private method was mocked, which I don't want if I can avoid it.) Here is an example of what I want to do.

public class UnderTest {

  public void methodPublic(){
    .....
    methodPrivate(aStringList);
    .....
  }

  private void methodPrivate(List<String> slist){
    //do stuff
  }
}

public class TestMyClass {

  @Tested
  UnderTest cut;

  @Mocked
  List<String> mockList;

  @Test
  public void testMyPublicMethod() {

    cut.methodPublic();

    new Verifications() {
      {
        // this doesnt work for me...
        invoke(cut, "methodPrivate", mockList);
        times = 1;
      }
    }
  }
}

Solution

  • You need a partial mock (you cannot avoid mocking the private method in this instance if you wish to know if it was triggered or not - a verification can only be done on a mocked method or instance). I have not used JMockit before but I expect the code would look something similar to:

    public class TestMyClass {
    
      @Tested
      UnderTest cut;
    
      @Mocked
      List<String> mockList;
    
      @Test
      public void testMyPublicMethod() {
    
        cut.methodPublic();
    
        new Expectations(UnderTest.class) {{
           cut.methodPrivate();
        }}
    
        new Verifications() {
          {
            // this should hopefully now work for you
            invoke(cut, "methodPrivate", mockList); //I assume here that you have statically imported the Deencapsulation class
            times = 1;
          }
        }
      }
    }