tags:

views:

85

answers:

3

There is a fail() method in JUnit4 library. I like it, but experiencing a lack of pass() method which is not present in the library. Why is it so?

I've found out that I can use assertTrue(true) instead but still looks unlogical.

@Test
 public void testSetterForeignWord(){
  try {
   card.setForeignWord("");
   fail();
  } catch (IncorrectArgumentForSetter ex){
  }

 // assertTrue(true);
 }
+13  A: 

As long as the test doesn't throw an exception, it passes, unless your @Test annotation specifies an expected exception. I suppose a pass() could throw a special exception that JUnit always interprets as passing, so as to short circuit the test, but that would go against the usual design of tests (i.e. assume success and only fail if an assertion fails) and, if people got the idea that it was preferable to use pass(), it would significantly slow down a large suite of passing tests (due to the overhead of exception creation). Failing tests should not be the norm, so it's not a big deal if they have that overhead.

Note that your example could be rewritten like this:

@Test(expected=IncorrectArgumentForSetter.class)
public void testSetterForeignWord("") throws Exception {
  card.setForeignWord("");
}

Also, you should favor the use of standard Java exceptions. Your IncorrectArgumentForSetter should probably be an IllegalArgumentException.

ColinD
The fail() method and assertX() methods really just throw an AssertionError, which causes the test method to exit uncleanly. That's why a successful return indicates success...
Steven Schlansker
-1 - pass() method is not doing nothing - it's quitting test immediately without exceptions. That would be effectively equivalent to return statement in most cases (except for expected exceptions, timeouts, etc.).
grigory
@grigory: You're right that a `pass()` method couldn't just do nothing, lest it be possible for a test to fail after calling it. So I removed that sentence.
ColinD
A: 

there is no need for the pass method coz when no AssertionFailedException is thrown from the test code the unit test case will pass. (The fail() method actually throws an AssertionFailedException to fail the testCase if control comes to that point)

Ajay
+3  A: 

Call return statement anytime your test is finished and passed.

Horcrux7
+1 must have been correct answer (in most cases with exception of expected, timeouts, etc.)
grigory