我已经使用 PowerMock/Mockito 模拟了私有(private)方法,现在我的问题是如何访问此方法内声明的对象?
例如。
private void method1()
{
MyObject ob = new MyObject();
}
现在在我的测试代码中我想访问 ob 对象来验证值。
最佳答案
This guide使用 PowerMock 模拟构造函数调用的详细信息:
... But with PowerMock you don't have to change the code, instead you can instruct PowerMock to intercept the call to new File(..) and return a mock object instead. To do this we start by creating a mock of type File.class as usual:
File fileMock = createMock(File.class);
To expect the call to new File we simply do:
expectNew(File.class, "directoryPath").andReturn(fileMock);
因此,就您的情况而言,您应该在测试用例或设置方法中包含这些内容:
MyObject mockOb = createMock(MyObject.class);
expectNew(MyObject.class).andReturn(mockOb);
通过添加这些,您将获得以下行为:
每当测试用例运行代码中存在new MyObject()
时,都会返回PowerMock模拟的对象实例。因此,在代码中的何处创建新的 MyObject
实例并不重要,它将与 createMock()
创建的实例完全相同功能。
编辑
lets take example
Class A { private void method1() { Obj obj = new Obj(); obj.setX(10); } //Here I want to access the obj object to verify the values }
要实现这一目标,您必须以不同的方式思考。
- 创建真实的A实例
- 为 Obj 构造函数设置模拟
- 运行触发
pruivate method1()
的逻辑 - 检查模拟 Obj 实例上的值
- 如果这些值不可测试(逻辑中有些东西修改了它),zou 可以检查 setX() 是否在适当的时间被调用。
大致如下:
@Test
public void testMyPrivateMethod() {
//1. object with the logic to test
A a = new A();
//2. set up mocking
Obj mockObj = createMock(Obj.class);
expectNew(Obj.class).andReturn(mockObj);
//3. trigger logic to test
a.someOtherMethodThatCallsMethod1();
//4. test Obj (find out if setX() has been called or not)
verify(mockObj).setX(any(Integer.class));
}
关于java - 如何访问私有(private)方法内部的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499877/