2

Okay so I'm building Test Cases for my project and I'm Using JUnit for testing. Now the problem I'm facing is that I need different set of arguments for different test cases of the same file.

public class ForTesting{
    //Test 1 should run on ips {1, true} and {2,true}
    @Test
    public void Test1()
    {
        //Do first Test case
    }
    //Test 2 should run on ips {3,true} and {4,true}
    @Test
    public void Test2()
    {
        //Do another Test case
    }
}

I know I can provide multiple arguments using parametrized arguments but the problem is the same set of arguments run for all the test cases. Is there a way to do this?

2 Answers 2

3

If you're not looking ONLY for standard junit parametrized tests, and depending on your company's legal policies you can use (at least) the following 2 libraries, which make things easier (both to implement and read):

1) JUnitParams (Apache 2)

@RunWith(JUnitParamsRunner.class)
public class PersonTest {

  @Test
  @Parameters({"17, false", 
               "22, true" })
  public void shouldDecideAdulthood(int age, boolean expectedAdulthood) throws Exception {
    assertThat(new Person(age).isAdult(), is(expectedAdulthood));
  }
}

2) Zohhak (LGPL) inspired by JUnit params but bringing some more sugar to the table (easy separator config, converters, etc)

@RunWith(ZohhakRunner.class)
public class PersonTest {

  @TestWith({"17, false", 
             "22, true" })
  public void shouldDecideAdulthood(int age, boolean expectedAdulthood) throws Exception {
    assertThat(new Person(age).isAdult(), is(expectedAdulthood));
  }
}


Credits: Examples above have been shamelessly copied and adjusted from JUnitParams' readme.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks thats what i needed!
@moldovean not yet, just read about it a while ago, but did not have the context for it so far
1

Few options:

Use Theories.

In a @Theory, use Assume.assumeThat.

@Theory
public void shouldPassForSomeInts(int param) {
     Assume.assumeTrue(param == 1 || param == 2);
}

@Theory
public void shouldPassForSomeInts(int param) {
     ...
}

Or use @TestedOn.

@Theory
public void shouldPassForSomeInts(@TestedOn(ints={1, 2}) int param) {
     ...
}

@Theory
public void shouldPassForSomeInts(@TestedOn(ints={3,4}) int param) {
     ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.