我正在尝试测试一个在构造函数中创建新对象的类。我正在使用 PowerMock 和 Mockito。
public ClassNeedToTest() throws Exception {
String targetCategory = "somevalue";
String targetService = "somevalue";
invoker = new ServiceInvoker(targetCategory, targetService); // throws Exception
}
对于上面给出的代码,我试图创建一个
ClassNeedToTest
的实例。测试该类的不同方法。我无法创建对象,因为 ServiceInvoker
创建正在抛出异常。 ServiceInvoker
类是第三方类。有什么方法可以模拟 ServiceInvoker,以便在测试类尝试创建
ClassNeedToTest
时我可以得到ServiceInvoker
的mock对象而不是真正调用 ServiceInvoker
的构造函数.在我的测试类中,我只是创建了一个 ClassNeedToTest 的新实例:
ClassNeedToTest obj = new ClassNeedToTest();
最佳答案
我找到了同样的答案。
如果你正确地按照下面给出的步骤,你可以模拟对象。
第1步。
- 添加注释以准备测试类。
@PrepareForTest({ ServiceInvoker.class, ClassNeedToTest.class})
第2步。
- 模拟类。
serviceInvokerMck = Mockito.mock(ServiceInvoker.class);
第 3 步。
调用 new 运算符时,使用以下方法模拟对象
PowerMockito.whenNew(ServiceInvoker.class).withAnyArguments().thenReturn(serviceInvokerMck);
我没有做的是添加类
ClassNeedToTest
在 PrepareForTest
认为应该在那里添加唯一需要模拟的类的注释。
关于junit - 需要在要测试的类的构造函数中模拟对象的创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216467/