Search code examples
javaunit-testinginstancio

With Instancio, how to ignore a superclass private property


I'm got a class B that extends an abstract class A. Class A has a private member that's initialized in the constructor.

public abstract class A {

  private String _dtoType;
  private String uuid = UUID.randomUUID().toString();

  public A() {
     this._dtoType = this.getClass().getSimpleName();
  }

  public String getDtoType() { return this._dtoType; }
  public String getUuid() { return this.uuid; }

}
public class B extends A {

  private String accountNumber;
  private String name;

  private C propC;
  private List<D> propDs;

  public B() {
     super();
  }

}

Assume that both C and D extend A, too.

I want to ignore both _dtoType and uuid for all classes. Say, if I'm creating an instance of B:

B item = Instancio.of(B.class)
                .generate(field(B::getAccountNumber), gen -> gen.text().pattern("#d#d#d#d#d#d#d#d"))
                .ignore(all(field("_dtoType")))
                .ignore(all(field("uuid")))
                .subtype(all(C.class), C.class)
                .subtype(all(D.class), D.class)
                .create();

But, I get an error:

Reason: invalid field '_dtoType' for class B

Solution

  • It looks like I have to be specific and reference the abstract class A in the ignore:

                    .ignore(all(field(A.class, "_dtoType")))
                    .ignore(all(field(A.class,"uuid")))