简体   繁体   English

如何访问私有方法内部的对象?

[英]How to access the object inside the private method?

I have mocked the private method using the PowerMock/Mockito , now my question here is how can I access the object declared inside this method ? 我使用PowerMock / Mockito模拟了私有方法,现在我的问题是如何访问此方法中声明的对象?

for example . 例如 。

private void method1()
{
MyObject ob = new MyObject();

}

now in my test code I want to access the ob object to verify the values . 现在在我的测试代码中,我想访问ob对象以验证值。

This guide details mocking a constructor call using PowerMock: 本指南详细介绍了如何使用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. ...但是使用PowerMock不必更改代码,而是可以指示PowerMock截获对新File(..)的调用并返回模拟对象。 To do this we start by creating a mock of type File.class as usual: 为此,我们像往常一样创建File.class类型的模拟:

 File fileMock = createMock(File.class); 

To expect the call to new File we simply do: 期望可以调用新文件,我们只需执行以下操作:

 expectNew(File.class, "directoryPath").andReturn(fileMock); 

So in your case, you should have these in your test case or setup method : 因此,在您的情况下,您应该在测试用例或设置方法中使用它们

MyObject mockOb = createMock(MyObject.class);
expectNew(MyObject.class).andReturn(mockOb);

By adding these, you will have the following behaviour: 通过添加这些,您将具有以下行为:

Whenever there is a new MyObject() in your code run by the test case, the object instance mocked by PowerMock will be returned. 每当测试用例运行的代码中有一个new MyObject() ,都会返回PowerMock模拟的对象实例。 So it does not matter where in your code you create a new MyObject instance, it will be the very same one created by the createMock() function. 因此在代码中的哪个位置创建新的MyObject实例并不重要,它与createMock()函数创建的实例完全相同。

EDIT 编辑

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 } 

To accomplish this, you have to think a bit differently. 要做到这一点,您必须有所不同。

  1. create real A instance 创建真实的A实例
  2. set up mocking for the Obj constructor 为Obj构造函数设置模拟
  3. run your logic that triggers the pruivate method1() 运行您的逻辑,触发逻辑pruivate method1()
  4. check the values on the mocked Obj instance 检查模拟的Obj实例上的值
    • if the values are not testable (something modifies it in the logic), zou could check if the setX() was called the appropriate times. 如果值不可测试(在逻辑上已对其进行了某些修改),则zou可以检查setX()是否被调用了适当的时间。

Something along these lines: 遵循以下原则:

@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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM