0

I created a parametrized JUnit test case. In this test case I defined the test cases in Object[][] each row represents one test case and all test cases will run at a time, now what I want is a way to run just one test case. let's say I want to run the 3rd test case so I want to tell junit to consider only the 2nd row of the object[][]? is there a way to do that?

Appreciate your response. Thanks

2 Answers2

1

Not sure what you mean but there are a few options:

  1. Use Theories instead of Parameterized that way you can mark some tests as @Test and others as @Theory.
  2. Use assume in the test to check the parameterized values apply to the test
  3. Use the Enclosed test runner and isolate some tests in one inner class that does Parameterized and other tests in another inner class.

Theories blog

Assume

Enclosed

John B
  • 32,493
  • 6
  • 77
  • 98
1

You can comment out the tests you don't want to run, like:

    @Parameters
    public static Collection stringVals() {
        return Arrays.asList(new Object[][] {
            //{"SSS"},
            //{""},
            //{"abcd"},
            {"Hello world"}  //only run this
        });
    }

EDIT: If you want to run different tests depending on the test cases, you can also ignore some test input with Assume class in JUnit 4+. Check this question

Example:

Let's assume that you have two instance of class Person, and you want to test if they are dressed. In case of sex.equals("male"), you want to check if his clothes list contains trousers, but for sex.equals("female"), you want to check if she has skirt contained in her list of clothes.

So, you can build test like:

@Parameter(0)
public Person instance;


@Parameters
public static Collection clothes() {
    Person alice = new Person();
    alice.setSex("female");
    alice.addClothes("skirt");
    Person bob = new Person();
    bob.setSex("male");
    bob.addClothes("trousers");
    return Arrays.asList(new Object[][] {
        {alice, "skirt"},
        {bob, "trousers"},
    });
}

@Test
public void testMaleDressed() {
    //Assume: ignore some test input. 
    //Note: Message is error output; when condition is satisfied, the following lines will run, if not: test ignored
    Assume.assumeTrue("Tested person: " + person + "is female, ignore!", instance.getSex().equals("male"));
    assertTrue(person.getClothes().contains("trousers"));
}

@Test
public void testFemaleDressed() {
    //Assume: ignore some test input. 
    //Note: Message is error output; when condition is satisfied, the following lines will run, if not: test ignored
    Assume.assumeTrue("Tested person: " + person + "is male, ignore!", instance.getSex().equals("female"));
    assertTrue(person.getClothes().contains("skirt"));
}

When you run all the tests, you will see

[0]
    - testMaleDressed(ignored)
    - testFemaleDressed(passed)

[1]
    - testMaleDressed(passed)
    - testFemaleDressed(ignored)

with no errors.

WesternGun
  • 11,303
  • 6
  • 88
  • 157