I want to write unit test for the class that I have. This class has an open method, and inside the public method there are calls for private methods in the same class. I want to mock the calls of these private methods. The class is similar to this:
public class SomeClass { public int somePublicMethod(int num) { int num2 = somePrivateMethod1(num); int num3 = somePrivateMethod2(num); return num2 + num3; } private int somePrivateMethod1(int num) { return 2*num; } private int somePrivateMethod2(int num) { return 3*num; } }
For my unit test, I am trying to use PowerMock with Mockito and TestNG. Here is my attempt at a test that checks somePublicMethod:
import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.spy; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.Test; @PrepareForTest(SomeClass.class) public class SomeClassTest { @Test public void testSomePublicMethod() throws Exception { int num = 4; SomeClass someClassSpy = spy(new SomeClass()); doReturn(8).when(someClassSpy, "somePrivateMethod1", num); doReturn(12).when(someClassSpy, "somePrivateMethod2", num); int result = someClassSpy.somePublicMethod(num); Assert.assertEquals(result, 20); } }
When I run this test, I get an exception and some tips:
FAILED: testSomePublicMethod org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:31) Eg thenReturn() may be missing. Examples of correct stubbing: when(mock.isOk()).thenReturn(true); when(mock.isOk()).thenThrow(exception); doThrow(exception).when(mock).someVoidMethod(); Hints: 1. missing thenReturn() 2. you are trying to stub a final method, you naughty developer!
I looked at a few examples on the Internet, but I did not find one that uses PowerMock with Mockito and TestNG specifically to do what I want. Can someone give me some guidance on what I could do differently?
source share