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

The junit5 module provides integration with the JUnit5 Test Framework (aka Jupiter).

ForgeExtension

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

@ExtendWith(ForgeExtension::class)
class FooTest {

}

Parameter Injection

The main feature of the extension is the possibility to inject parameters in your test methods:

@ExtendWith(ForgeExtension::class)
class FooTest {

    @Test
    fun `test with random int`(@IntForgery(min = 13, max = 42) i: Int) {
        //
    }

    @Test
    fun `test with random int`(@Forgery foo: Foo) {
        //
    }
}

You can inject :

Property / Field injection

Using the any of the annotation mentionned above 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.

@ExtendWith(ForgeExtension::class)
class FooTest {

    @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 @ForgeConfiguration annotation on your test class and set the seed. In case of a test failure, the seed that was used for the failing test will be printed in the error stream.

@ExtendWith(ForgeExtension::class)
@ForgeConfiguration(seed = 0xdeadL)
class FooTest {

}

Custom Factories

Chances are, you'll need to forge more than primitives or Strings. To do so you'll need to use Factories. A simple way to provide that to the extension is to use the @ForgeConfiguration on your test class and set a custom configurator class as the value.

@ExtendWith(ForgeExtension::class)
@ForgeConfiguration(MyConfigurator::class)
class FooTest {

    //

}

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