https://kotlinlang.org logo
#kotest
Title
# kotest
a

André Martins

01/24/2023, 5:08 PM
Hey is it possible to generate a random instance based on a class using Arb? something like Arb.next<MyType>()?
e

Emil Kantis

01/24/2023, 5:09 PM
Yes. Arb.bind or Arb.data (Alias for bind)
Copy code
Arb.bind(
  <http://Arb.int|Arb.int>(),
  Arb.string(codepoints = Codepoint.alphanumeric()),
  ::Student
)
Another option:
Copy code
Arb.data<Student>(providedArbs = mapOf(String::class to Codepoint.alphanumeric()))
a bit tricky when using String for instance, since the provided arbs will work for all values of that type
a

André Martins

01/25/2023, 10:14 AM
Ya true
d

Davio

01/25/2023, 10:14 AM
You can also use DataFaker to have some more realistic names and combine that with your custom generator 🙂
a

André Martins

01/25/2023, 10:15 AM
I just wanted to override a specific field without the need to define every arb for every field with
arbitrary
block
d

Davio

01/25/2023, 10:23 AM
I guess you could do it like this:
Copy code
val studentArb = arbitrary {
            val student = Arb.data<Student>().bind()
            student.copy(name = Arb.string(codepoints = Codepoint.alphanumeric()).bind())
        }
But I agree it would be good to have more control over the generation for specific fields
The providerArbs in Arb.data works on types, not field names, so some sort of generator with field names could be useful
In this case the example is small enough that I wouldn't mind a simple arbitrary and just map the fields explicitly
e

Emil Kantis

01/25/2023, 10:26 AM
Reflective binding with overriding per field should be doable I think. Worth investigating
a

André Martins

01/25/2023, 10:32 AM
I totally agree for instance im having issues because the default Arb for OffsetDateTime uses too much memory resulting in out of memory exception in my unit tests 😛
d

Davio

01/25/2023, 10:35 AM
Probably due to the zoneOffsets 🙂
e

Emil Kantis

01/25/2023, 9:57 PM
Created a POC.. definitely seems doable 🙂
Shit.. I was hoping the cast would filter out properties for irrelevant classes, but seems to pass due to type-erasure 😞 nvm, solved. was possible to reflectively check the type of the property to make sure it matched the class being constructed
107 Views