Skip to main content
Version: 10.x

Constructor Selection Policy

When AutoParams generates instances of complex types that have multiple constructors, it follows a specific policy to determine which constructor to use:

  1. Constructors annotated with @ConstructorProperties are prioritized.
  2. If no such annotation is present, AutoParams chooses the constructor with the fewest parameters.

Here's an example:

@Getter
public class ComplexObject {

private final int value1;
private final String value2;
private final UUID value3;

@ConstructorProperties({ "value1", "value2", "value3" })
public ComplexObject(int value1, String value2, UUID value3) {
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
}

@ConstructorProperties({ "value1", "value2" })
public ComplexObject(int value1, String value2) {
this(value1, value2, null);
}

public ComplexObject(int value1) {
this(value1, null, null);
}
}
@Test
@AutoParams
void testMethod(ComplexObject object) {
assertNotNull(object.getValue2());
assertNull(object.getValue3());
}

In this example, AutoParams selects the constructor with the @ConstructorProperties annotation that has the fewest parameters—(int, String)—and assigns null to the value3 field. This shows how constructor selection can affect the structure of the generated object.