Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run parameterized JUnit tests with different Parameters

I have a JUnit-Test that looks like this:

private final User user1;
private final User user2;

public UserTest(User user1, User user2) {
    this.user1 = user1;
    this.user2 = user2;
}

@Parameterized.Parameters
public static Collection<Object[]> userData() {
    return Arrays.asList(new Object[][] {
            { new User("Tim", "Burton", "tim.burton"),
                    new User("tim", "burton", "timothy.burton") },
            { new User("Vincent", "van Gogh", "vincent.van.gogh"),
                    new User("vincent", "van-gogh", "vincent.vangogh") } });
}

@Test
public void testPositive() {
    checkMatching(user1, user2);
}

Now all the tests are successful, but I want to create a second List of @Parameterized.Parameters for the negative tests. The new method should look like this:

@Test
public void testNegative() {
    checkFalseMatching(wrongUser1, wrongUser2);
}

Is it possible to use a method-specific parameters? I would use the parameters I've already created for the testPositive() method and the second list of parameters for the testNegative() method.

How can I do that? Can I use a "scope" for my parameters or something similar?

like image 265
muffin Avatar asked Dec 31 '25 14:12

muffin


2 Answers

You can also try junitparams. With junitparams you can parameterise tests via a method that returns parameter values.

like image 143
Rafal Avatar answered Jan 02 '26 03:01

Rafal


A couple options here. First take in 3 or 4 parameters in your constructor...

public UserTest(User equalUser1, User equalUser2, 
          User notEqualUser1, User notEqualUser2);

Another option would be to use the @Enclosed running and separate the different set of Parameters / tests into separate inner classes. This is generally a good practice anyway since if you have a mix of parameterized tests and non-parameterized tests you would not want to run the non-parameterized tests multiple times.

Another option is to use Theories and to use the assumeThat method to check that the arguments are in a specific set.

Example Theory with assumeThat

like image 28
John B Avatar answered Jan 02 '26 02:01

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!