Java 模拟构建器模式外部类中存在的方法(单元测试)

Java 模拟构建器模式外部类中存在的方法(单元测试),java,unit-testing,mockito,testng,builder-pattern,Java,Unit Testing,Mockito,Testng,Builder Pattern,我正试图找出一种方法,在下面的构建器中模拟用于单元测试的方法 public class A { private C ObjectC; private D ObjectD; public getObjectC() { // This should not be executed in Unit test as object creation involves external systems. // The object C creation depends up

我正试图找出一种方法,在下面的构建器中模拟用于单元测试的方法

public class A  {
  private C ObjectC;
  private D ObjectD; 

  public getObjectC() {
    // This should not be executed in Unit test as object creation involves external systems.
    // The object C creation depends upon the properties set by Withers inside the inner Builder class.
    return new C();
  }

  public A(ABuilder builder) {
    this.ObjectD = builder.ObjectD;
    this.ObjectC = geObjectC();
  }

  // Similarly there are three for* methods.
  public D forXYZ(final String xyz) {
    this.ObjectD.setXYZ(xyz);
    // Sometimes based on the property of XYX, the value of ABC changes.
    this.ObjectD.setABC(null);
    return this.ObjectD;
  }

  public static class ABuilder() {
    private D ObjectD;

    // Similar to the below wither method, I have four Withers with few branch logic to built Object D
    public A withFoo(final String foo) {
      this.ObjectD.setFoo(foo);
      return this;
    }

    public A build() { 
      return new A(this);
    }
  }
我的单元测试课

A ObjectA = new A.ABuilder().withFoo("foo").build();
assertEquals(A.getObjectD().getFoo(),"foo");
// Similarly assert other properties of Object D. This assertion is required as the property values varies based on what the user passes in the wither.
// Eg : If 'even' is set for value 10, 'odd' is set for value 5.

D ObjectD = A.forXYZ("Request");
ObjectD.doSomething();

// Now assert the properties of D and see if proper XYZ is set.
// Similarly I have two three for* methods inside A used for modifying the property of D after creation.

// The inside builder takes care of the creation of ObjectD with properties that are going to be set only once and changes very rarely. Where as the outside class A has for* methods which handles the setters of other properties which are going to be set multiple times.

D ObjectD = A.forXYZ("Request");
ObjectD.doSomethingXYZ();
A.forABC("RequestId").doSomethingABC();

尝试使用Spy,但它没有模仿内部getObjectC方法

@Mock C ObjectC;
A a = spy(new A());
doReturn(ObjectC).when(A).getObjectC();
目前正在使用TestNG和Mockito进行单元测试。我不想使用PowerMockito来实现这一点。
如何模拟上述用例?

我不明白您想要实现什么。你的ABILDER是一个静态类,你不需要a的am实例。我将a的实例返回给使用库的用户类。在我没有明确提到的类中,我还有一些其他的实例变量和方法。你将无法模拟构造函数中发生的事情。考虑将C作为参数替代。@第二,我可以将C作为参数传递给A的构造函数。这将导致内部生成器类的逻辑不能完全覆盖。我们希望A的消费者仅在Builder类的帮助下构造A。我想在构建类时复制准确的消费者行为。那么您要测试的到底是什么?请发布完整的最小测试用例。