Attila is right for most cases. What you want to test is that the creature really does what you think it should do, not how it does it. The case that you have here is: "I already know that baseCreate does what I want it to do, so I don’t want to repeat it just to be called." It may be so, but if so, then your superclass really collaborates more. This is one of the reasons for the delegation to inherit. However, it is sometimes difficult to go back and change this design decision, so you need to check what you have.
You still prefer to simply verify that "create" does what you want in general, but you might have a case where baseCreate really does a lot of things that require a lot of collaborators and such that makes it difficult and fragile to tests. In this case, you would like to use "spy". The spy wraps the "real" object and delegates calls to the real method, unless you specifically create another wait.
If you can make baseCreate public, you can use Mockito as follows:
@RunWith(MockitoJUnitRunner.class) // We prepare PartialMockClass for test because it final or we need to mock private or static methods public class YourTestCase { @Spy private Derived classUnderTest = new Derived(); @Test public void privatePartialMockingWithPowerMock() { MyObject myObject = new MyObject(); when(classUnderTest.baseCreate(myObject)).thenReturn(myObject); // execute your test classUnderTest.create(myObject); verify(classUnderTest).baseCreate(myObject); } }
If you cannot make baseCreate public, I think you could use PowerMock . It allows you to test private methods, but I don’t think that for some reason it could not protect methods.
@RunWith(PowerMockRunner.class) // We prepare PartialMockClass for test because it final or we need to mock private or static methods @PrepareForTest(Derived.class) public class YourTestCase { @Test public void testCreate() { Derived classUnderTest = PowerMockito.spy(new Derived()); MyObject myObject = new MyObject(); // use PowerMockito to set up your expectation PowerMockito.doReturn(myObject).when(classUnderTest, "baseCreate", myObject); // execute your test classUnderTest.create(myObject); // Use PowerMockito.verify() to verify result PowerMockito.verifyPrivate(classUnderTest).invoke("baseCreate", myObject); } }
source share