我想为我上课写一个单元测试.这个类有一个公共方法,在public方法中,在同一个类中调用私有方法.我想模拟对这些私有方法的调用.该类与此类似:
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;
}
}
对于我的单元测试,我试图将PowerMock与Mockito和TestNG一起使用.这是我尝试测试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);
}
}
当我运行此测试时,我得到一个异常和一些提示:
FAILED: testSomePublicMethod
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:31)
E.g. 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!
我在网上查看了一些例子,但我没有找到一个将Mockito和TestNG专门用于PowerMock来做我想做的事情.有人可以给我一些关于我能做些什么的指示吗?