Quantcast
Channel: User blacktide - Stack Overflow
Viewing all articles
Browse latest Browse all 49

Answer by blacktide for Why Junit fails to perform dependency injection in test?

$
0
0

Your final code block is correct and is the standard practice, you don't need a constructor in this test class for the Calculator instance.

For the test class you should define the fields and initialize them in a @BeforeAll or @BeforeEach method.

Using a constructor for a test class in JUnit is reserved for parameterized unit tests, which is why you are getting an error stating that you're missing a ParameterResolver. This would be an example where you would use a constructor for a parameterized test:

public class Calculator {    public int subtract(int a, int b) {        return a - b;    }}@RequiredArgsConstructor@RunWith(Parameterized.class)class CalculatorTest {    private final int x;    private final int y;    private final int z;    private Calculator calculator;    // Constructor is generated by lombok with @RequiredArgsConstructor    // and accepts three parameters, x, y, and z    @BeforeEach    void setUp() {        calculator = new Calculator();    }    @Test    void testSubtract() {        assertEquals(z, calculator.subtract(x, y));    }    /**     * This method will pass each parameter into the constructor     * of this test class. In this case, the testSubtract method     * will be ran 4 times with each set of parameters.     */    @Parameterized.Parameters    static Collection parameters() {        return Arrays.asList(            new Object[][] {               {5, 3, 2},               {10, 1, 9},               {120, 40, 80},               {1, 1, 0}            }        );    }}

You can find additional details about Parameterized Unit Testing here for JUnit 4 and here for JUnit 5.


Viewing all articles
Browse latest Browse all 49

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>