Skip to content

How to generate random subtype instances of a given type? #1126

Answered by armandino
bash-spbu asked this question in Q&A
Discussion options

You must be logged in to vote

@bash-spbu Instancio selects random subtypes only for sealed abstract types. You can find more info here:

https://www.instancio.org/user-guide/#subtype-mapping

Since you're not using sealed types, you can achieve something similar by creating a helper method:

static Supplier<Vehicle> vehicleSupplier() {
    return () -> {
        Class<?> subtype = Instancio.gen()
                .oneOf(Car.class, Bicycle.class, Boat.class)
                .get();

        return Instancio.of(Vehicle.class)
                .subtype(all(Vehicle.class), subtype)
                .create();
    };
}

List<Vehicle> vehicles = Stream.generate(vehicleSupplier())
        .limit(100)
        .collect(Collectors.to…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@bash-spbu
Comment options

Answer selected by bash-spbu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants