Search code examples
javajmockit

JMockit verify if private method is called


I am testig a public method and I want to verify if a private method, that have mocked params, is called. All the answers I have found are using invoke method, but this was removed since JMockit v1.36

public class ClassToTest{

   public void methodToTest(){
     DependencyClass abc = new DependencyClass();
     if(privateMethod1()){
        privateMethod2(abc);
     }
   }
   
   private boolean privateMethod1(){ return true; }
   
   private void privateMethod2(DependencyClass abc){ abc.doStuff(); }
}

public class testClassToTest{
   
   @Mocked
   DependencyClass abc;
   
   @Tested 
   ClassToTest testedClass;

   @BeforeEach
   public void setUp() { 
     testedClass = new ClassToTest();
   }
    
   @Test
   public void testMethod(){
        new MockUp<ClassToTest>() {
            @Mock
            private boolean privateMethod1() {
                return true;
            }
        };
        
        testedClass.methodToTest();

        new FullVerificationsInOrder() {{
            abc = new DependencyClass();
            //Check here if privateMethod2(abc) gets called once
        }};
   }

Solution

  • You can use Powermock to mock and verify private methods.

    Please check https://github.com/powermock/powermock/wiki/MockPrivate