0
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?
       }

   }

}
4
  • why not putting it member? Commented Nov 5, 2017 at 12:12
  • Sure, that would work. But how/where that member is set? Commented 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 example Commented 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()" Commented Nov 5, 2017 at 13:54

1 Answer 1

1

InnerTests won't be beneath the parameterized test in the test tree:

enter image description here

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
           })
       )));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.