Home > front end >  How to pass expected and actual value in paramererized test in JUnit 5
How to pass expected and actual value in paramererized test in JUnit 5

Time:05-25

I am trying to implement Parameterized test in which I have a set of input and expected values which I want to test using assertEquals method of JUnit. I'm using JUnit version 5.x for this I am passing the input value to my custom method defined in other package (that I'm testing) and I am checking it with an expected value with assertEquals method.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runners.Parameterized.Parameters;

class StringHelperTest {
    private StringHelper helper = new StringHelper();
    private String input;
    private String expectedOutput;

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getExpectedOutput() {
        return expectedOutput;
    }

    public void setExpectedOutput(String expectedOutput) {
        this.expectedOutput = expectedOutput;
    }

    @Parameters
    public static Collection<String[]> testConditions() {
        String[][] expectedOutputs = { { "AACD", "CD" }, { "ACD", "CD" }, { "CDEF", "CDEF" }, { "CDAA", "CDAA" } };
        return Arrays.asList(expectedOutputs);
    }

    @ParameterizedTest
    @Test
    public void truncateAInFirst2Positions_A_atStart() {
        assertEquals(expectedOutput, helper.truncateAInFirst2Positions(input));

    }
}

In the method testConditions() the actual and expected values are given as a 2 dimensinonal String array expectedOutputs {{<actual_value>,<expected_value>},{...}}.

How do I pass expectedOutputs array to the truncateAInFirst2Positions_A_atStart() method to test all conditions mentioned in expectedOutputs array

CodePudding user response:

With JUnit 5 you have ParameterizedTest and a Source for the input parameters, which are simple the parameters of the method.

So you want a Method with this signature:

@ParameterizedTest
//Source Annotation
void truncateAInFirst2Positions_A_atStart(String actual, String expected) {

And now you look up a for your use case matching source. When you want to proivde your test data with your method you could use @MethodSource("testConditions"). The String in the annotation points to the static method providing your test data. The test will be executed x times where x is the count of pairs in your collection. The elements in your String Array will be used as method arguments.

For simple types like Strings a CSV source can be simpler and easier to read:

@CsvSource({
"AACD, CD",
"ACD, CD"
})

You can check all possible sources and possiblites in the offcial documentation: https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests

  • Related