kotlininstancio

Instancio - Select.field("<field>") does not work if field is on an abstract parent


I have a class I'm creating with Instancio. I have an abstract parent with an id field.

When I test with Instancio, I cannot set the "id" field to null.

@MappedSuperclass
abstract class EntityWithId {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    @Column(name = "id")
    var id = 0
}

@Entity
@Table(name = "child")
class ChildEntity : EntityWithId() {
    @Basic
    @Column(name = "created")
    var isCreated = false
...
Instancio.of(ChildEntity::class.java)
    .set(Select.field("id"), null) // Fails

However, if I move id into ChildEntity the instancio code works.

How do I select the field in the parent class?


Solution

  • When you specify only the field name like Select.field("id"), Instancio assumes that the field belongs to the class you're creating, that is ChildEntity.

    In this case the field is defined in the superclass, so you will need to specify the class explicitly:

    Instancio.of(ChildEntity::class.java)
        .set(Select.field(EntityWithId::class.java, "id"), null)
        // snip...
    

    Since you're using Kotlin, consider defining a utility class so you can also avoid referring to fields as strings, e.g. field(EntityWithId::id):

    https://www.instancio.org/user-guide/#kotlin-method-reference-selector

    Example: https://github.com/instancio/instancio/blob/main/instancio-tests/kotlin-tests/src/test/kotlin/org/instancio/test/kotlin/KSelectorsTest.kt