interface MyInterface {}
static class ImplA implements MyInterface {}
static class ImplB implements MyInterface {}
class OuterTests {
@ParameterizedTest
@MethodSource("myInterfaceProvider")
void test(MyInterface myInterface) {}
static Stream<MyInterface> myInterfaceProvider() {
return Stream.of(new ImplA(), new ImplB());
}
@Nested
class InnerTests{
@Test
void nestedTest() {
//how to access myInterface:MyInterface?
}
}
}
-
why not putting it member?Mzf– Mzf2017-11-05 12:12:02 +00:00Commented Nov 5, 2017 at 12:12
-
Sure, that would work. But how/where that member is set?cnmuc– cnmuc2017-11-05 12:37:12 +00:00Commented Nov 5, 2017 at 12:37
-
You can use @Parameter for Field injection, see more example here: github.com/junit-team/junit4/wiki/parameterized-tests if you want I can give a full exampleMzf– Mzf2017-11-05 13:07:49 +00:00Commented Nov 5, 2017 at 13:07
-
@Parameter(s) is Junit4. I don't want to mix both libraries 4 and 5 (or is it recommended?). In 5, I could create a (constructor) ParameterResolver, but I don't know how to inject both objects "new ImplA()" and "new ImplB()"cnmuc– cnmuc2017-11-05 13:54:29 +00:00Commented Nov 5, 2017 at 13:54
Add a comment
|
1 Answer
InnerTests won't be beneath the parameterized test in the test tree:
Thus, you cannot pass the argument of the test method to the nested test class.
Here's a way to define tests for interfaces in JUnit Jupiter:
interface MyInterfaceTests {
MyInterface newInstance();
@Test
default void test() {
MyInterface instance = newInstance();
// test something
}
}
class ImplATests implements MyInterfaceTests {
@Override
public MyInterface newInstance() {
return new ImplA();
}
}
class ImplBTests implements MyInterfaceTests {
@Override
public MyInterface newInstance() {
return new ImplB();
}
}
Alternatively, you can write it using @TestFactory:
@TestFactory
Stream<DynamicNode> test() {
return Stream.of(new ImplA(), new ImplB())
.map(instance -> dynamicContainer(instance.getClass().getSimpleName(), Stream.of(
dynamicTest("test 1", () -> {
// test something
}),
dynamicTest("test 2", () -> {
// test something else
})
)));
}
