0

In the class I am testing, there are a few assert statements that check for various conditions.

One of the methods is

GetNames(string id){
    assert(! id.Equals("")); // Causes all junit tests to stop
    ...
}

and there is an assert statement to check if id is not blank.

In my unit tests, I have one test where I pass it a blank string, and a few others. The problem is that when the assert statement gets executed in the class, the JUnit tests stop running after that test case.

How can I change/setup the unit tests so that if there is an assertion failure in the class, the tests do not stop.

I have to enable the assertions in order for the code to run properly since there are cases where variables are incremented in the assertions. Unfortunately, I cannot change any of the code.

I am using the JUnit plugin in eclipse. I do not have any code in the setup and teardown sections.

randomThought
  • 6,203
  • 15
  • 56
  • 72

1 Answers1

4

If you have assert statements in the code being tested, and assertions are enabled, then those statements will be causing an AssertionError to be thrown. You can catch that in your test code and ignore it:

try {
    xxx.GetNames("");
} catch (AssertionError e) {
    // this is expected - ignore it
}
Richard Fearn
  • 25,073
  • 7
  • 56
  • 55
  • Thanks. I just realized the code which is causing the tests to stop actually calls "system.exit(1)". Is there a way to still run the unit tests after system.exit has been called? – randomThought Nov 06 '10 at 23:09
  • 2
    No, it causes the VM to terminate. What is the code that you're testing? Any library code that calls `System.exit` is broken. – Richard Fearn Nov 06 '10 at 23:16
  • Actually, you could write your own `SecurityManager` that prohibits a call to `System.exit`. See for instance http://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit – Richard Fearn Nov 06 '10 at 23:21
  • If the intent is to verify that the exception is thrown, you need to call `fail()` after calling `GetNames`. If the intention is to ignore the assertion failure, then whatever `GetNames` does might not have been completed, so it would be questionable to do that in a test (where you wanted to know the intended state of your objects before you make assertions) – NamshubWriter Nov 08 '10 at 15:15