Skip to content
Xavier Gouchet edited this page Sep 3, 2020 · 2 revisions

The junit4 module provides integration with the JUnit4 Test Framework.

ForgeRule

When writing a JUnit4 test, you can add a ForgeRule to your test class to benefit from the library.

class FooTest {
    @get:Rule
    val forge = ForgeRule()
}

Property / Field injection

Using one of the […]Forgery annotation on a lateinit var property (or a non final Java field), you can have that property/field injected for each test methods automatically. This is usefull when you need a random input of the same type on all your test functions.

You can inject :

class FooTest {

    @get:Rule
    val forge = ForgeRule()

    @Forgery
    lateinit var fakeFoo: Foo

    @IntForgery
    lateinit var fakeIntList: List<Int>

    @StringForgery
    lateinit var fakeStringSet: Set<String>

    @MapForgery(
        key = AdvancedForgery(string = [StringForgery(StringForgeryType.HEXADECIMAL)])
    )
    lateinit var fakeFooMap: Map<String, Foo>

}

Reproducible tests

Whenever a test fails, or just to reproduce the same test exactly, you can use the seed parameter of the ForgeRule constructor. In case of a test failure, the seed that was used for the failing test will be printed in the error stream.

class FooTest {

    @get:Rule
    val forge = ForgeRule(0xdeadL)

}

Custom Factories

Chances are, you'll need to forge more than primitives or Strings. To do so you'll need to use Factories. You can configure your ForgeRule instance like any Forge instance, or using a custom configurator.

class FooTest {

    @get:Rule
    val forge = ForgeRule(SEED).apply { MyConfigurator().configure(this) }

    //

}

class MyConfigurator : ForgeConfigurator {
    override fun configure(forge: Forge) {
        forge.addFactory(Foo::class.java, FooFactory())
        forge.addFactory(Bar::class.java, BarFactory())
    }
}