Search code examples
javajunitverificationjmockit

Verifying that a protected super method is invoked


I have the following structure:

class Bar{
  ....
  protected void restore(){
    ....
  }

  ....
}

This class is extended by Foo as below:

class Foo extends Bar{
    ....

    @Override
    public void restore(){  //valid override
        super.restore();

        ....
    }
}

In my jUnit test I would like to test that when foo.restore() is called, the super.restore() is called subsequently. Hence, below is my jUnit test method:

class FooTest{
  @Tested
  Foo _foo;

  @Test
  void testRestore(final Bar bar){

    new Expectations(){{
      bar.restore(); times = 1; // Error! bar.restore() not visible
    }};

    Deencapsulation.invoke(_foo,"restore");
  }
}

Unfortunately, my test cannot compile. The reason is that 1) the restore() of the parent is protected and 2) FooTest and Foo exist together in a separate project (and therefore folder) vs. Bar.

Is there anyway to achieve the desired test? I have checked the jMockit tutorials (many times over the past few months) and have not seen a similar test (same goes for a search on Google).


Update

With the help of the responses, I understand that enforcing subclasses to invoke super is not the best practice, yet this is not my implementation and I still have to test it. I am still looking for a way to enforce my jUnit test to check if the call to the parent is taking place.


Solution

  • The following test should work:

    public class FooTest
    {
        @Tested Foo _foo;
    
        @Test
        void restoreInFooCallsSuper(@Mocked final Bar bar)
        {
            new Expectations() {{
                invoke(bar, "restore");
            }};
    
            _foo.restore();
        }
    }