我使用PowerMock模拟了一个构造函数。
@RunWith(PowerMockRunner.class)
@PrepareForTest(SubjectClass.class)
class SomeClassTest {
@Mock
SubjectClass subjectObject;
@InjectMock
SomeClass someObject;
...
@Test
public void testMethod_inp_exp() throws Exception {
PowerMock.whenNew(SubjectClass.class).withAnyArguments().thenReturn(subjectObject);
when(subjectObject.subjectMethod(someParameters).thenReturn(null);
assertThat(someObject.someMethod(someOtherParam).isEqualTo(someCondition);
}
}
这不足以模拟构造函数吗?有什么遗漏。
因为,我已在someMethod中使用Mockito.mockingDetails(subjectObject).isMock()
验证了代码,并且我正在调用false
。
答案 0 :(得分:3)
docs明确声明为了模拟构造函数,你应该:
使用
PowerMockito.whenNew
,例如whenNew(MyClass.class).withNoArguments().thenThrow(new IOException("error message"));
请注意,您必须准备创建新实例的类
MyClass
用于测试,而不是MyClass
本身。例如。如果班级做新的MyClass()
被称为X
,那么您必须@PrepareForTest(X.class)
为了让whenNew
起作用:@RunWith(PowerMockRunner.class) @PrepareForTest(X.class) public class XTest { @Test public void test() { whenNew(MyClass.class).withNoArguments().thenThrow(new IOException("error message")); X x = new X(); x.y(); // y is the method doing "new MyClass()" .. } }
因此,在您的情况下,您需要将@PrepareForTest(SubjectClass.class)
替换为@PrepareForTest(SomeClass.class)
答案 1 :(得分:-1)
SubjectClass subjectClassMock=EasyMock.createNiceMock(SubjectClass.class);
PowerMock.expectNew(SubjectClass.class,<your arguments for constructor>).andReturn(subjectClassMock);
确保在@PrepareForTest中添加SubjectClass和SomeClass并执行PowerMock.replayAll();