Home > database >  How to implement dependency injection with JUnit 5?
How to implement dependency injection with JUnit 5?

Time:10-30

I was trying to follow multiple tutorials about the subject but I cannot understand how they support DI. To my basic understanding, DI should be supported by supplying extended/implemented classes object to the test, so the test will be able to be executed with multiple variations of the objects.

For example:

@Test
public void myTest(Base baseObj){
   assertThis(baseObj);
   assertThat(baseObj);
}

class Base {
  //data
  //methods
}

class Class1 extends Base{}
class Class2 extends Base{}
class Class3 extends Base{}

There should be a way to supply objects of the derived classes to the test. Am I wrong till here?

I couldn't understand from the explanations, how TestInfo class for example (or the other classes) helps me with that?

Can you enlighten me please?

CodePudding user response:

You can do it like this:

public class Test1 {
    @ParameterizedTest
    @MethodSource("myTest_Arguments")
    public void myTest(Base baseObj){
        System.out.println(baseObj);
    }

    static Stream<Arguments> myTest_Arguments() {
        return Stream.of(
            Arguments.of(new Class1()),
            Arguments.of(new Class2()),
            Arguments.of(new Class3()));
    }
}
  • Related