Annotation Interface WithSettings
This annotation must be placed on a Settings field.
There can be at most one field annotated @WithSettings per class.
The annotated field may be static or non-static. Prior to version 6.0.0,
a static field was required if the test class contained a @ParameterizedTest
method; this restriction no longer applies.
@ExtendWith(InstancioExtension.class)
class ExampleTest {
@WithSettings
private final Settings settings = Settings.create()
.set(Keys.COLLECTION_MIN_SIZE, 50)
.set(Keys.COLLECTION_MAX_SIZE, 100);
@Test
void example() {
}
}
@Nested Test Classes
Prior to version 6.0.0, settings defined in @Nested
test classes were independent from those in their outer classes.
Since version 6.0.0, when @WithSettings is used in
@Nested test classes, the inner class settings are overlaid on
top of the outer class settings. In other words, settings defined in the
inner class override any matching settings from the outer class, for example:
@WithSettings
private final Settings outer = Settings.create()
.set(Keys.STRING_MIN_LENGTH, 3)
.set(Keys.STRING_MAX_LENGTH, 20);
@Nested
class InnerTest {
@WithSettings
private final Settings inner = Settings.create()
.set(Keys.STRING_MIN_LENGTH, 10);
// Effective value of STRING_MIN_LENGTH = 10 and STRING_MAX_LENGTH = 20
}
Inheritance
Since version 6.0.0, settings declared by a superclass or an
implemented interface are inherited by subclasses. This allows a common
set of settings to be shared by extending a base test class:
abstract class BaseTest {
@WithSettings
protected final Settings settings = Settings.create()
.set(Keys.STRING_MIN_LENGTH, 3)
.set(Keys.STRING_MAX_LENGTH, 20);
}
@ExtendWith(InstancioExtension.class)
class ExampleTest extends BaseTest {
// Effective value of STRING_MIN_LENGTH = 3 and STRING_MAX_LENGTH = 20
}
As with @Nested test classes, inherited settings are merged
rather than replaced: a subclass that declares its own @WithSettings
field overrides only the matching settings, and inherits the rest.
@ExtendWith(InstancioExtension.class)
class ExampleTest extends BaseTest {
@WithSettings
private final Settings settings = Settings.create()
.set(Keys.STRING_MIN_LENGTH, 10);
// Effective value of STRING_MIN_LENGTH = 10 and STRING_MAX_LENGTH = 20
}
When both mechanisms are combined, settings are applied from the outermost enclosing class down to the test class itself, and within each class from its supertypes down to the class itself. In other words, the closer a declaration is to the test class being executed, the higher its precedence.
- Since:
- 1.1.1