Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (10.2k points)

OK, so the @Ignore annotation is good for marking that a test case shouldn't be run.

However, sometimes I want to ignore a test based on runtime information. An example might be if I have a concurrency test that needs to be run on a machine with a certain number of cores. If this test were run on a uniprocessor machine, I don't think it would be correct to just pass the test (since it hasn't been run), and it certainly wouldn't be right to fail the test and break the build.

So I want to be able to ignore tests at runtime, as this seems like the right outcome (since the test framework will allow the build to pass but record that the tests weren't run). I'm fairly sure that the annotation won't give me this flexibility, and suspect that I'll need to manually create the test suite for the class in question. However, the documentation doesn't mention anything about this and looking through the API it's also not clear how this would be done programmatically (i.e. how do I programmatically create an instance of Test or similar that is equivalent to that created by the @Ignore annotation?).

If anyone has done something similar in the past or has a bright idea of how else I could go about this, I'd be happy to hear about it.

1 Answer

0 votes
by (46k points)

The JUnit method is to do that at run-time is org.junit.Assume.

 @Before

 public void beforeMethod() {

     org.junit.Assume.assumeTrue(someCondition());

     // rest of setup.

 }

You can create it in a @Before way or in the test itself, but not in an @After method. If you do it in the test itself, your @Before program will get run. You can additionally do it within @BeforeClass to limit class initialization.

An assumption of failure creates the test to be neglected.

 To correlate with the @RunIf annotation from JUnit-ext, their sample code would resemble similar to this:

@Test

public void calculateTotalSalary() {

    assumeThat(Database.connect(), is(notNull()));

    //test code below.

}

Not to state that it is much simpler to carry and use the connection from the Database.connect() approach this way.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...