Skip to content
Xavier Gouchet edited this page Feb 17, 2020 · 3 revisions

The core module provide the implementation of the Forge class which is the main feature of Elmyr.

Forge

A Forge instance will work as a factory to help you generate random data. By default, it can only forge primitives, Strings, Collections and Enums. It can also be extended with custom factories to forge your own classes.

The seed

One of the main purpose of Elmyr is to be able to reproduce failing tests, event with random data. That's why every Forge instance has a seed value that can be use to set its state. Two forges with the same seed will generate the same data.

To set the seed manually, you can use the seed property :

    forge.seed = 123456789L

In most test framework integrations, a failing test will print the automatic seed that made the test fail in the standard error stream. Eg:

<FooTest.bar()> failed with Forge seed 0x4815162342
Add the following line in your @Before method to reproduce :
forge.setSeed(0x4815162342L);

Default features

A Forge allow you to generate many simple reproducible random data : Primitives, Strings, Collections and Enum values. You can find a full list of what's available in the class's reference

Factories

For your own custom types, you can add an implementation of a ForgeryFactory, allowing the Forge to generate those custom types according to your own rules.

data class Foo(val i: Int, val s: String)

class FooForgeryFactory : ForgeryFactory<Foo> {
	override fun getForgery(forge: Forge): Foo {
        return Foo(forge.aPositiveInt(), forge.anHexadecimalString())
    }
}

val forge = Forge().apply {
	addFactory(FooForgeryFactory())
}

Kotlin Delegates

Some delegates are available to take advantage of the Kotlin language. To use them, make sure that your class implements the ForgeryAware interface. You can then use the following delegate properties: