简体   繁体   English

Mockito / PowerMockito模拟私有工厂方法

[英]Mockito/PowerMockito mocking private factory method

I want to use pattern 1 suggested in the following link: https://code.google.com/p/mockito/wiki/MockingObjectCreation and have the following class: 我想使用以下链接中建议的模式1: https//code.google.com/p/mockito/wiki/MockingObjectCreation并具有以下类:

public class MyClass {
  private AnyType anyObject;
  private Foo foo; // Foo is a thirdparty class

  public MyClass(AnyType anyObject) {
    //...
    foo = makeFoo();
  }

  private Foo makeFoo() {
    return new Foo();
  }
}

I'm trying to make a test as follows: 我正在尝试进行如下测试:

@Test
public void myTestMethod() {
  MyClass myClass = Mockito.spy(new MyClass());

  // now i want to do something like this:
  Foo mockFoo= Mockito.mock(Foo.class);
  // Mockito.doReturn(mockFoo).when(myClass).makeFoo());
}

The problem is my factory method makeFoo is a private method, so I can't access it. 问题是我的工厂方法makeFoo是私有方法,所以我无法访问它。 I don't want to make it public just for the test. 我不想只是为了考试而公开。 My test classes are not in the same package as my productive code either, so making it visible only for the package won't work. 我的测试类与生产性代码也不在同一个包中,因此仅在该包中可见对我来说是行不通的。

Update: Now i found another problem. 更新:现在我发现了另一个问题。 Assumed that makeFoo() is public, 'mockFoo' will not be returned either, yet the real makeFoo() method is invoked. 假设makeFoo()是公共的,则也不会返回'mockFoo',但是会调用真正的makeFoo()方法。 This happens since the invocation of makeFoo() (in the constructor of MyClass) is prior to the creation of mockFoo. 发生这种情况是因为在创建嘲笑Foo之前​​调用了makeFoo()(在MyClass的构造函数中)。

Does anyone know how to solve this problem or am I doing something totally wrongly? 有人知道如何解决这个问题,还是我做错了什么?

Thanks you guys in advance for helping!! 预先感谢你们的帮助!

If you just need to set a field inside your class, it's doable with MockitoAnnotations 如果您只需要在类中设置一个字段,则可以使用MockitoAnnotations

You just need to create fields you need, annotate them and in unit test before section call MockitoAnnotations.initMocks(this) 您只需要创建所需的字段,对其进行批注并在单元测试中进行部分调用,然后再调用MockitoAnnotations.initMocks(this)

In your case it will look like: 在您的情况下,它将看起来像:

 @Spy
 @InjectMocks
 MyClass myClass;
 @Mock
 Foo foo;

 @Before
 public void initMocks() {
     MockitoAnnotations.initMocks(this);
 }

Please read also documentation above. 请同时阅读上面的文档。

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

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