Junit4 - xgouchet/Elmyr GitHub Wiki
The junit4 module provides integration with the JUnit4 Test Framework.
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()
}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 :
- Primitives (or collections of primitives), using
@BoolForgery,@IntForgery,@LongForgery,@FloatForgeryor@DoubleForgery; - Strings (or collections of Strings), using
@StringForgery; - Maps, using
@MapForgery - Any object, enum (or collection of objects or enums) (assuming the extension has an appropriate factory),
using
@Forgery; - A
Forgeinstance, without annotation needed.
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>
}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)
}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())
}
}