无论构造函数签名如何,都模拟 class 的属性

Mocking an attribute of a class regardless of constructor signature

Class

public class Foo {
  private MyClass obj;

  public Foo(String s, int i, boolean b) {
    MyOtherClass otherObj = OtherClassFactory.getInstance();
    this.obj = new MyClass(s, i, b, otherObj);
  }

  //More Code
}

构造函数接受一些参数,从工厂中检索一个实例,并使用所有这些局部变量来实例化它具有的一个属性 (obj)。

然而,我只关心嘲笑obj本身。我不关心构造函数的任何参数,也不关心 otherObj.

我试过只注入属性:

public class FooTest {
  @Mock
  private MyClass fakeObj;
  @InjectMocks
  private Foo foo;

  //More Code
}

但是这样不行,抱怨:

Cannot instantiate @InjectMocks field named 'foo' of type 'class Foo'. You haven't provided the instance at field declaration so I tried to construct the instance. However the constructor or the initialization block threw an exception : OtherClassFactory has not been initialized.

我正在尝试做的事情是否可行,如果可行,如何实现?如果没有,我需要模拟 OtherClassFactory,我该怎么做?

我会提供第二个构造函数,package-private,就像这样。

public Foo(String s, int i, boolean b) {
    this(new MyClass(s, i, b, OtherClassFactory.getInstance());
}

Foo(MyClass obj) {
   this.obj = obj;
}

然后在你的测试中,你可以只写

Foo toTest = new Foo(mockMyClass);

其中 mockMyClass 是您的 Mockito 模拟。