pri05
pri05

Reputation: 99

Create entity test object with constraints using Instancio for junit test cases

I'm trying to create test objects for an entity class. Below is the entity class which has all the constraints for the fields as per the database table.

@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "persons", schema = "vetting_service")
@Getter
@Setter
@NoArgsConstructor
@Slf4j
@ToString(onlyExplicitlyIncluded = true)
public class PersonEntity extends AuditableEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    @Null(groups = OnCreate.class)
    @NotNull(groups = OnUpdate.class)
    @ToString.Include
    private Long id;

    @Column(name = "source_person_id")
    @Size(max = Person.SOURCE_ID_MAXLENGTH)
    @ToString.Include
    private String sourcePersonId;

    @Column(name = "first_name")
    @NotBlank
    @Size(max = Person.FIRST_NAME_MAXLENGTH)
    private String firstName;

    @Column(name = "middle_name")
    @Size(max = Person.MIDDLE_NAME_MAXLENGTH)
    @NullOrNotBlank
    private String middleName;

    @Column(name = "last_name")
    @NotBlank
    @Size(max = Person.LAST_NAME_MAXLENGTH)
    private String lastName;

    /**
     * SSN. Not updatable!
     */
    @Column(name = "ssn", length = 72, updatable = false)
    @NotBlank
    @Size(min = Person.SSN_LENGTH, max = Person.SSN_LENGTH)
    @Pattern(regexp = "^\\d{9}$", message = "must be a nine digit string")
    @Convert(converter = AttributeEncryptor.class)
    private String ssn;

    @Column(name = "ssn_last_4", updatable = false)
    @NotBlank
    @Size(max = 4)
    private String ssnLast4;

    @Column(name = "dob")
    @NotNull
    @Past
    private LocalDate dateOfBirth;

    @ElementCollection
    @CollectionTable(name = "addresses", schema = "vetting_service", joinColumns = @JoinColumn(name = "PERSON_ID"))
    @MapKeyEnumerated(EnumType.STRING)
    @PhysicalAddressRequired
    private Map<AddressType, @Valid AddressEmbeddable> addresses = new HashMap<>();

    /**
     * The home phone of the individual to be vetted.
     */
    @ElementCollection
    @CollectionTable(name = "phones", schema = "vetting_service", joinColumns = @JoinColumn(name = "PERSON_ID"))
    @MapKeyEnumerated(EnumType.STRING)
    private Map<PhoneType, @Valid PhoneEmbeddable> phones = new HashMap<>();

    /**
     * The home phone of the individual to be vetted.
     */
    @ElementCollection
    @CollectionTable(name = "email_addresses", schema = "vetting_service", joinColumns = @JoinColumn(name = "PERSON_ID"))
    @MapKeyEnumerated(EnumType.STRING)
    private Map<EmailAddressType, @Valid EmailAddressEmbeddable> emailAddresses = new HashMap<>();

    @SuppressWarnings("checkstyle:magicnumber")
    public void setSsn(@NotNull final String ssn) {
        this.ssn = ssn;
        this.ssnLast4 = StringUtils.right(ssn, 4);
    }

    /**
     * Convenience method to get PHYSICAL address, which can never be null.
     *
     * @return The PHYSICAL address.
     */
    public AddressEmbeddable physicalAddress() {
        return this.addresses.get(AddressType.PHYSICAL);
    }
}

When I try to create test object using instancio

final PersonEntity tstPerson = Instancio.of(PersonEntity.class).create();

I'm not getting data with constraints like length. First Name generated exceed the length that is set. How can I create data for this object that complies the constraints?


Edit: I tried settings with Instancio JPA_enabled

final PersonEntity tstPerson = Instancio.of(PersonEntity.class)
                .withSetting(Keys.BEAN_VALIDATION_ENABLED, true)
                .withSetting(Keys.JPA_ENABLED, true)
                .create();

I still see below error, looks like these settings are not getting reflected, am I missing anything here?

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated in table 'master.persons', column 'first_name'. Truncated value: 'JQHQJNFUMRWKUNRQQJEPHNGNREYILYFHHZNFZKABGAHZQZNIOESPEMQZVFYJCMPLTEYUVGAKPLLFDFEDJAVAPBDLFWQPINOEQVTA'.

Upvotes: 1

Views: 134

Answers (1)

armandino
armandino

Reputation: 18562

You can achieve this by enabling a couple of settings:

PersonEntity person = Instancio.of(PersonEntity.class)
    .withSetting(Keys.BEAN_VALIDATION_ENABLED, true)
    .withSetting(Keys.JPA_ENABLED, true)
    .create();

These can also be enabled in instancio.properties to avoid doing it manually every time you create an object. Please see the docs for details:

Upvotes: 0

Related Questions