304

I know that one way to do it would be:

@Test
public void foo() {
   try {
      // execute code that you expect not to throw Exceptions.
   } catch(Exception e) {
      fail("Should not have thrown any exception");
   }
}

Is there any cleaner way of doing this? (Probably using Junit's @Rule?)

Andrii Abramov
  • 7,967
  • 8
  • 55
  • 79
Ankit Dhingra
  • 5,084
  • 6
  • 25
  • 33
  • 12
    A JUnit test is judged to have failed if it throws any exception other than an expected exception. Usually no exceptions are expected. – Raedwald Jul 20 '13 at 21:26
  • Isn't there a distinction between failure and error in JUnit? The first means the test failed, the second means something unexpected happened. – Vituel Aug 21 '14 at 12:33
  • 1
    possible duplicate of [How can I test if a particular exception is not thrown?](http://stackoverflow.com/questions/8575653/how-can-i-test-if-a-particular-exception-is-not-thrown) – Ciro Santilli新疆棉花TRUMP BAN BAD Feb 10 '15 at 13:30

17 Answers17

238

You're approaching this the wrong way. Just test your functionality: if an exception is thrown the test will automatically fail. If no exception is thrown, your tests will all turn up green.

I have noticed this question garners interest from time to time so I'll expand a little.

Background to unit testing

When you're unit testing it's important to define to yourself what you consider a unit of work. Basically: an extraction of your codebase that may or may not include multiple methods or classes that represents a single piece of functionality.

Or, as defined in The art of Unit Testing, 2nd Edition by Roy Osherove, page 11:

A unit test is an automated piece of code that invokes the unit of work being tested, and then checks some assumptions about a single end result of that unit. A unit test is almost always written using a unit testing framework. It can be written easily and runs quickly. It's trustworthy, readable, and maintainable. It's consistent in its results as long as production code hasn't changed.

What is important to realize is that one unit of work usually isn't just one method but at the very basic level it is one method and after that it is encapsulated by other unit of works.

enter image description here

Ideally you should have a test method for each separate unit of work so you can always immediately view where things are going wrong. In this example there is a basic method called getUserById() which will return a user and there is a total of 3 unit of works.

The first unit of work should test whether or not a valid user is being returned in the case of valid and invalid input.
Any exceptions that are being thrown by the datasource have to be handled here: if no user is present there should be a test that demonstrates that an exception is thrown when the user can't be found. A sample of this could be the IllegalArgumentException which is caught with the @Test(expected = IllegalArgumentException.class) annotation.

Once you have handled all your usecases for this basic unit of work, you move up a level. Here you do exactly the same, but you only handle the exceptions that come from the level right below the current one. This keeps your testing code well structured and allows you to quickly run through the architecture to find where things go wrong, instead of having to hop all over the place.

Handling a tests' valid and faulty input

At this point it should be clear how we're going to handle these exceptions. There are 2 types of input: valid input and faulty input (the input is valid in the strict sense, but it's not correct).

When you work with valid input you're setting the implicit expectancy that whatever test you write, will work.

Such a method call can look like this: existingUserById_ShouldReturn_UserObject. If this method fails (e.g.: an exception is thrown) then you know something went wrong and you can start digging.

By adding another test (nonExistingUserById_ShouldThrow_IllegalArgumentException) that uses the faulty input and expects an exception you can see whether your method does what it is supposed to do with wrong input.

TL;DR

You were trying to do two things in your test: check for valid and faulty input. By splitting this into two method that each do one thing, you will have much clearer tests and a much better overview of where things go wrong.

By keeping the layered unit of works in mind you can also reduce the amount of tests you need for a layer that is higher in the hierarchy because you don't have to account for every thing that might have gone wrong in the lower layers: the layers below the current one are a virtual guarantee that your dependencies work and if something goes wrong, it's in your current layer (assuming the lower layers don't throw any errors themselves).

Jeroen Vannevel
  • 41,258
  • 21
  • 92
  • 157
  • 3
    The thing is that I am trying to TDD and one of the collaborators that I use is throwing an exception. So I need to test the fact that I am consuming the exception thrown by the collaborator – Ankit Dhingra Jul 18 '13 at 18:36
  • 7
    Are you saying your functionality is dependent on the handling of an exception? That's a code smell: exceptions are there to elegantly let you catch issues; they're not used for flow control. If you want to test a scenario in which an exception should be thrown then you should use the `expected` annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use `expected` and perhaps use asserts to determine if it's been resolved. – Jeroen Vannevel Jul 18 '13 at 18:38
  • The thing is that I cannot recover from the exception that has occurred in the collaborator and all I do is just log the issue using a log.debug("Error message"). So there are no side effects happening as a part of the catch block that I can possibly assert on. – Ankit Dhingra Jul 18 '13 at 18:42
  • 8
    @JeroenVannevel it is perfectly valid to test that an error situation which cause an exception to be thrown is properly handled. – Thorbjørn Ravn Andersen Jul 18 '13 at 18:44
  • @AnkitDhingra: So what exactly is the problem? You're saying that the error is handled by logging, which is probably trough an external library. You can't (shouldn't) be testing those: if that's all there is to it then you should just use `expected` and check if the exception occurred. @ThorbjørnRavnAndersen: Definitely, I'm not disputing that. But as far as I have seen from his problem description, there is no reason to do this here (and it contradicts his title). – Jeroen Vannevel Jul 18 '13 at 18:49
  • But which unit test would break when I remove the try catch? The other unit tests have mocked the collaborator so no exception would be thrown. How would you test the fact that you have put in a try catch? – Ankit Dhingra Jul 18 '13 at 19:11
  • You don't have to test implementation; you have to test functionality. Create a test for this method that should work and add all necessary asserts. Then create a test with `expected` and call the method with incorrect data. If both turn up green you should assume the logging works as well (most logging frameworks have their own tests). If you perform error handling other than logging then you might want to consider adding asserts to check if this was correctly resolved. You shouldn't explicitly check if your catch-block was called: that's implementation, not functionality. – Jeroen Vannevel Jul 18 '13 at 19:17
  • @JeroenVannevel As far as I can tell you can't compile the java if you don't write your own try/catch blocks around code that could throw exceptions. So you're forced to do try {} catch(Exception e) { fail() }. –  Sep 22 '13 at 17:34
  • @AnkitDhingra if you want to verify that your code catches and logs an exception thrown by a collaborator, then have your test 1) mock the collaborator, 2) tell the mock to throw a specific exception, 3) use the API of your logging code to attach a log handler, 4) call your code, and 5) assert that the exception was logged – NamshubWriter Aug 07 '15 at 04:59
  • 1
    @dpk yes you can. You add `throws IllegalArgumentException` to your test. What you want in the end, is that your test turns red if there is an exception. Well, guess what? You do not need to write `fail()`. As @Jeroen Vannevel wrote: _"if an exception is thrown the test will automatically fail."_ – Amedee Van Gasse Feb 18 '16 at 16:21
  • There are plenty of situations where an exception can be caught and handled as "not important", for instance if we are querying for some optional value and the error can be treated as "don't know". Sometimes just calling the code and checking that the result is correct will be the correct test; but there are also some times when conceptually the correct test is "it did not pass on the exception" and in these cases a "assertDoesNotThrow" test as described by @Groostav seems appropriate. – Richard Whitehead Dec 08 '17 at 10:59
  • The problem I find with this approach is that if my unit-test failed and throw an exception,I get a bad error message from junit - "java.lang.RuntimeException: test should never throw an exception to this level". I don't even know which test failed. which is real bad – Nir May 01 '18 at 06:01
  • @RichardWhitehead - If you think there are plenty of situations where it makes sense to test for no exceptions, then please write an answer for it. The optional example is not clear. Throwing an exception for an optional might not even be needed and it might be symptom of a problem in the code under test. Please provide details in your answer. – armani Mar 24 '20 at 21:45
  • Great answer. This opened my eyes towards the correct unit testing philosophy. When I started doing TDD I would write tests for failures, I need to move away from that. I guess this is similar to the idea of "programming to exceptions". – Brendan Sluke Sep 05 '20 at 20:55
  • 1
    @Nir made a relevant point. While testing to the core level that fails before testing higher levels, the principle breaks down when the lower level that fails in within an external package. From the perceptive of the application under test, 'that package fails when doing this' is all that matters, the internal tests need to be added within the package – innov8 Oct 14 '20 at 00:03
180

I stumbled upon this because of SonarQube's rule "squid:S2699": "Add at least one assertion to this test case."

I had a simple test whose only goal was to go through without throwing exceptions.

Consider this simple code:

public class Printer {

    public static void printLine(final String line) {
        System.out.println(line);
    }
}

What kind of assertion can be added to test this method? Sure, you can make a try-catch around it, but that is only code bloat.

The solution comes from JUnit itself.

In case no exception is thrown and you want to explicitly illustrate this behaviour, simply add expected as in the following example:

@Test(expected = Test.None.class /* no exception expected */)
public void test_printLine() {
    Printer.printLine("line");
}

Test.None.class is the default for the expected value.

Sven Döring
  • 2,636
  • 1
  • 7
  • 14
  • 44
    I think this is the best answer. The accepted answer is great, and the author is correct to point out the code smell. However he didn't really answer the specific question. – HellishHeat Aug 02 '17 at 10:10
  • 5
    it is interesting to note that the default value for the expected is None, so just annotating the method with @Test would do. – oziomajnr Dec 23 '19 at 19:14
  • 6
    @oziomajnr Just annotating the method with `@Test` does nothing to help with the SonarQube problem. – David Conrad Aug 06 '20 at 20:30
  • This is exactly the same problem as I had. While I totally agree with @jeroen-vannevel 's answer I needed some sort of validation to make sure SonarQube does not raise any issues. – Ernani Mar 24 '21 at 19:28
  • 1
    Adding same solution for Junit5: `assertDoesNotThrow(() -> Printer.printLine("line"));` – Ankush May 18 '21 at 17:17
108

JUnit 5 (Jupiter) provides three functions to check exception absence/presence:

assertAll​()

Asserts that all supplied executables
  do not throw exceptions.

assertDoesNotThrow​()

Asserts that execution of the
  supplied executable/supplier
does not throw any kind of exception.

  This function is available
  since JUnit 5.2.0 (29 April 2018).

assertThrows​()

Asserts that execution of the supplied executable
throws an exception of the expectedType
  and returns the exception.

Example

package test.mycompany.myapp.mymodule;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class MyClassTest {

    @Test
    void when_string_has_been_constructed_then_myFunction_does_not_throw() {
        String myString = "this string has been constructed";
        assertAll(() -> MyClass.myFunction(myString));
    }
    
    @Test
    void when_string_has_been_constructed_then_myFunction_does_not_throw__junit_v520() {
        String myString = "this string has been constructed";
        assertDoesNotThrow(() -> MyClass.myFunction(myString));
    }

    @Test
    void when_string_is_null_then_myFunction_throws_IllegalArgumentException() {
        String myString = null;
        assertThrows(
            IllegalArgumentException.class,
            () -> MyClass.myFunction(myString));
    }

}
M-Razavi
  • 2,489
  • 1
  • 30
  • 42
oHo
  • 41,098
  • 25
  • 141
  • 183
69

With AssertJ fluent assertions 3.7.0:

Assertions.assertThatCode(() -> toTest.method())
    .doesNotThrowAnyException();
Xaerxess
  • 25,634
  • 7
  • 81
  • 101
denu
  • 1,458
  • 17
  • 25
30

Java 8 makes this a lot easier, and Kotlin/Scala doubly so.

We can write a little utility class

class MyAssertions{
  public static void assertDoesNotThrow(FailingRunnable action){
    try{
      action.run()
    }
    catch(Exception ex){
      throw new Error("expected action not to throw, but it did!", ex)
    }
  }
}

@FunctionalInterface interface FailingRunnable { void run() throws Exception }

and then your code becomes simply:

@Test
public void foo(){
  MyAssertions.assertDoesNotThrow(() -> {
    //execute code that you expect not to throw Exceptions.
  }
}

If you dont have access to Java-8, I would use a painfully old java facility: aribitrary code blocks and a simple comment

//setup
Component component = new Component();

//act
configure(component);

//assert 
/*assert does not throw*/{
  component.doSomething();
}

And finally, with kotlin, a language I've recently fallen in love with:

fun (() -> Any?).shouldNotThrow() 
    = try { invoke() } catch (ex : Exception){ throw Error("expected not to throw!", ex) }

@Test fun `when foo happens should not throw`(){

  //...

  { /*code that shouldn't throw*/ }.shouldNotThrow()
}

Though there is a lot of room to fiddle with exactly how you want to express this, I was always a fan of fluent assertions.


Regarding

You're approaching this the wrong way. Just test your functionality: if an exception is thrown the test will automatically fail. If no exception is thrown, your tests will all turn up green.

This is correct in principle but incorrect in conclusion.

Java allows exceptions for flow of control. This is done by the JRE runtime itself in APIs like Double.parseDouble via a NumberFormatException and Paths.get via a InvalidPathException.

Given you've written a component that validates Number strings for Double.ParseDouble, maybe using a Regex, maybe a hand-written parser, or perhaps something that embeds some other domain rules that restricts the range of a double to something specific, how best to test this component? I think an obvious test would be to assert that, when the resulting string is parsed, no exception is thrown. I would write that test using either the above assertDoesNotThrow or /*comment*/{code} block. Something like

@Test public void given_validator_accepts_string_result_should_be_interpretable_by_doubleParseDouble(){
  //setup
  String input = "12.34E+26" //a string double with domain significance

  //act
  boolean isValid = component.validate(input)

  //assert -- using the library 'assertJ', my personal favourite 
  assertThat(isValid).describedAs(input + " was considered valid by component").isTrue();
  assertDoesNotThrow(() -> Double.parseDouble(input));
}

I would also encourage you to parameterize this test on input using Theories or Parameterized so that you can more easily re-use this test for other inputs. Alternatively, if you want to go exotic, you could go for a test-generation tool (and this). TestNG has better support for parameterized tests.

What I find particularly disagreeable is the recommendation of using @Test(expectedException=IllegalArgumentException.class), this exception is dangerously broad. If your code changes such that the component under test's constructor has if(constructorArgument <= 0) throw IllegalArgumentException(), and your test was supplying 0 for that argument because it was convenient --and this is very common, because good generating test data is a surprisingly hard problem--, then your test will be green-bar even though it tests nothing. Such a test is worse than useless.

Groostav
  • 2,871
  • 1
  • 20
  • 27
  • 2
    (regarding the use of expected exception) Since JUnit 4.13, you can use `Assert.assertThrows` to check that some code throws an exception. – MageWind Mar 23 '17 at 01:05
25

If you are unlucky enough to catch all errors in your code. You can stupidly do

class DumpTest {
    Exception ex;
    @Test
    public void testWhatEver() {
        try {
            thisShouldThrowError();
        } catch (Exception e) {
            ex = e;
        }
        assertEquals(null,ex);
    }
}
Ben Tennyson
  • 549
  • 5
  • 17
  • 1
    Just a small suggestion, `Exception ex` should be `= null;` before you can test it. – Denees Jun 26 '15 at 12:37
  • 4
    This isn't a great solution. If the method that shouldn't throw an exception does throw, you won't get a useful error message. Just call the method that shouldn't throw an exception, and test it's return value (or side effects, like logging the exception). If it later unexpectedly throws an exception, the test will fail. – NamshubWriter Aug 07 '15 at 04:55
  • 5
    Or just put Assert.fail() in the catch, easier and prettier IMO. – isaac.hazan Nov 17 '15 at 12:06
  • Yes, I agree with you. One more way is add an annotation on top of method @Test (expected = InvalidRequestException.class) – Ben Tennyson Nov 18 '15 at 19:45
  • This is very useful for me, thank you. In my situation i am asserting inside `Awaitility`'s `untilAsserted(ThrowingRunnable assertion)`. The method I call does always throw an exception at first, but I want to assert that it will stop doing so eventually (according to Awaitility's parameters) – Ubeogesh Jun 17 '20 at 13:16
  • Agree, this an ugly solution but at least it makes SonarLint happy. – Jasper Citi Jul 21 '20 at 10:04
19

Although this post is 6 years old now, however, a lot has changed in the Junit world. With Junit5, you can now use

org.junit.jupiter.api.Assertions.assertDoesNotThrow()

Ex:

public void thisMethodDoesNotThrowException(){
   System.out.println("Hello There");
}

@Test
public void test_thisMethodDoesNotThrowException(){
  org.junit.jupiter.api.Assertions.assertDoesNotThrow(
      ()-> thisMethodDoesNotThrowException()
    );
}

Hope it will help people who are using newer version of Junit5

Dinesh Arora
  • 1,652
  • 2
  • 20
  • 27
  • I wish there was a way to specify concrete exception class here. I have to do this inside `Awaitility`'s `untilAsserted(ThrowingRunnable assertion)`. System under test is currently throwing a specific exception on the ThrowingRunnable I provide, but I want to give it some time until it stops doing so. However if it would throw a different exception I would like the test to fail instantly. – Ubeogesh Jun 17 '20 at 13:23
8

JUnit5 adds the assertAll() method for this exact purpose.

assertAll( () -> foo() )

source: JUnit 5 API

razalghul
  • 89
  • 2
  • 4
4

To test a scenario with a void method like

void testMeWell() throws SomeException {..}

to not throw an exception:

Junit5

assertDoesNotThrow(() -> {
    testMeWell();
});
pirho
  • 8,805
  • 12
  • 34
  • 44
2

Use assertNull(...)

@Test
public void foo() {
    try {
        //execute code that you expect not to throw Exceptions.
    } catch (Exception e){
        assertNull(e);
    }
}
Mike Rapadas
  • 4,347
  • 2
  • 26
  • 20
  • 6
    I'd say this is misleading. The catch block is never reached, so the `assertNull` is never executed either. However the quick reader gets the impression that an assertion is made that really verifies the non-throwing case. In other words: if the catch block is reached, the exception is always non-null - it can thus be replaced by a simple `fail`. – Andreas Nov 14 '16 at 10:08
  • 1
    misleading indeed, ..... but wait, ... oh I see ... `assertNull(e)` will report the test as failed, as as stated `e` can't be `null` in the `catch` block ... Mike this is just weird programming :-/ ... yes at least use `fail()` like Andreas says – Julien Jun 12 '17 at 15:15
1

If you want to test that whether your test target consumes the exception. Just leave the test as (mock collaborator using jMock2):

@Test
public void consumesAndLogsExceptions() throws Exception {

    context.checking(new Expectations() {
        {
            oneOf(collaborator).doSth();
            will(throwException(new NullPointerException()));
        }
    });

    target.doSth();
 }

The test would pass if your target does consume the exception thrown, otherwise the test would fail.

If you want to test your exception consumption logic, things get more complex. I suggest delegating the consumption to a collaborator which could be mocked. Therefore the test could be:

@Test
public void consumesAndLogsExceptions() throws Exception {
    Exception e = new NullPointerException();
    context.checking(new Expectations() {
        {
            allowing(collaborator).doSth();
            will(throwException(e));

            oneOf(consumer).consume(e);
        }
    });

    target.doSth();
 }

But sometimes it's over-designed if you just want to log it. In this case, this article(http://java.dzone.com/articles/monitoring-declarative-transac, http://blog.novoj.net/2008/09/20/testing-aspect-pointcuts-is-there-an-easy-way/) may help if you insist tdd in this case.

Yugang Zhou
  • 6,423
  • 5
  • 27
  • 47
1

You can expect that exception is not thrown by creating a rule.

@Rule
public ExpectedException expectedException = ExpectedException.none();
LazerBanana
  • 5,377
  • 3
  • 22
  • 44
  • ExpectedExceptions are used to assert thrown exceptions. The code you provide is just to initialise the rule so you can add your requirements for the assertions. This code itself does not add any value at all. The javadoc also states this: " /** * Returns a {@linkplain TestRule rule} that expects no exception to * be thrown (identical to behavior without this rule). */" So it will have the exact same result as without it. – Pim Hazebroek Oct 13 '17 at 10:52
  • I agree with you, and would not use it that way, but it is possible to assert that no exception has been thrown. If the test passes there should be enough to say that the exception has not been thrown, but in other hand if there is a question there must be a need for it. And rarely but still sometimes is good to have it visible. What if code and circumstances changed and we have no test for some particular edge case? – LazerBanana Oct 13 '17 at 11:04
  • I'm curious to see how you would assert that with expected exception. And yes, if requirements change and you have no test for a particular edge case you're screwed ;-) always cover all corner cases. – Pim Hazebroek Oct 13 '17 at 12:35
  • what do you mean? you don't assert on it, you expect it. In this case, you expect no exception. Not sure what you on about. – LazerBanana Oct 16 '17 at 13:19
1

This may not be the best way but it definitely makes sure that exception is not thrown from the code block that is being tested.

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class AssertionExample {

    @Test
    public void testNoException(){
        assertNoException();
    }    

    private void assertException(){
        Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
    }

    private void assertNoException(){
        Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
    }

    private void doNotThrowException(){
        //This method will never throw exception
    }
}
MLS
  • 357
  • 1
  • 3
  • 13
1

I faced the same situation, I needed to check that exception is thrown when it should, and only when it should. Ended up using the exception handler to my benefit with the following code:

    try {
        functionThatMightThrowException()
    }catch (Exception e){
        Assert.fail("should not throw exception");
    }
    RestOfAssertions();

The main benefit for me was that it is quite straight forward and to check the other way of the "if and only if" is really easy in this same structure

  • Welcome to SO. Your question was flagged for 'Late Answer' review as the question is 7 years old and has 17 other answers. Whilst your answer may provide some value, very late answers will often be downvoted. – GoodJuJu Dec 16 '20 at 13:43
0

You can do it by using a @Rule and then call method reportMissingExceptionWithMessage as shown below: This is Scala code.

enter image description here

Crenguta S
  • 466
  • 9
  • 10
  • 1
    ```private val```? What is this language? Clearly not Java ;p And please, do not provide code as a screenshot, it is not welcomed. – Andremoniy Jul 29 '19 at 09:47
  • I see you've mentioned it is Scala, but saying that it can be *easily done* in Java is not a strong argument, I am sorry – Andremoniy Jul 29 '19 at 09:49
  • I removed the part that bothered you. I will try to replace the image also. Haven't figured out how to add code yet.. – Crenguta S Jul 30 '19 at 11:47
-1

You can create any kind of your own assertions based on assertions from junit:

static void assertDoesNotThrow(Executable executable) {
    assertDoesNotThrow(executable, "must not throw");
}
static void assertDoesNotThrow(Executable executable, String message) {
    try {
        executable.execute();
    } catch (Throwable err) {
        fail(message);
    }
}

And test:

//the following will succeed
assertDoesNotThrow(()->methodMustNotThrow(1));
assertDoesNotThrow(()->methodMustNotThrow(1), "fail with specific message: facepalm");
//the following will fail
assertDoesNotThrow(()->methodMustNotThrow(2));
assertDoesNotThrow(()-> {throw new Exception("Hello world");}, "Fail: must not trow");

Generally speaking there is possibility to instantly fail("bla bla bla") the test in any scenarios, in any place where it makes sense. For instance use it in a try/catch block to fail if anything is thrown in the test case:

try{methodMustNotThrow(1);}catch(Throwable e){fail("must not throw");}
//or
try{methodMustNotThrow(1);}catch(Throwable e){Assertions.fail("must not throw");}

This is the sample of the method we test, supposing we have such a method that must not fail under specific circumstances, but it can fail:

void methodMustNotThrow(int x) throws Exception{
    if (x == 1) return;
    throw new Exception();
}

The above method is a simple sample. But this works for complex situations, where the failure is not so obvious. There are the imports:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.*;
armagedescu
  • 1,178
  • 2
  • 13
  • 21
  • There are fairly better option to check that assertion haven't been thrown which don't involve creating custom code. @Rule is one of them – Vargan Oct 30 '19 at 13:32
  • @Vargan I've pointed the method to create your own assertions in the way it is Designed By JUnit especially for the purposes to create your own assertions. JUnit provides that by design, especially for that purpose, to create your own rules, extend the behavior of JUnit with asserts that are not yet implemented. Because not everything is implemented in this world These assertions work identically as JUnit assertion works in terms of passing or failing as well as reporting failures. – armagedescu Mar 26 '20 at 10:16
-2

The following fails the test for all exceptions, checked or unchecked:

@Test
public void testMyCode() {

    try {
        runMyTestCode();
    } catch (Throwable t) {
        throw new Error("fail!");
    }
}
Rocky Inde
  • 1,351
  • 16
  • 24