1

I did search for this already, but only found one topic on NUnit. I guess JUnit still is a bit different to NUnit so I am going foreward to ask my question ;-)

I have one test case with a setUp(), a test() and a tearDown(). Instead of throwing exeptions in the setUp() and test() I use the function fail("Some text here..."); Also there are some asserts because of which the test might teminate. Now I want to get the reason for failure of the test case in the tearDown() function (which is a prolbem) and then write it as a string into a file (which would be no problem if I could get the failure reason). My question is, how can I access information about the failure of a test case? How can I even check if a test failed at all in the tearDown() function?

Regards, SH

  • Could you give us your code that you have at the moment? – Max May 22 '13 at 03:36
  • the `tearDown()` method is not supposed to give information about failures. That's the job of the `TestRunner` – Marco Forberg May 22 '13 at 07:35
  • I know that the tearDown method should not habe the information about failures but as I only habe one test method a test runner would seem a bit big of an issue. Also I want a documentation for each test case not the whole test suite. – Sebastian Hätälä May 22 '13 at 12:04

1 Answers1

1

Here is the programmatic way you could do this.

Throwable thrownException = null;

@Before
public void setup{ thrownException = null; }

@Test
public void test(){
    try{
         // do test here
    } catch (Throwable t){
        thrownException = t;
        throw t;
    }
}

@After 
public void cleanup(){
      if (thrownException != null)
            ....
}

Another option would be to create a custom Rule that would do what you need in the case of a failure.

John B
  • 32,493
  • 6
  • 77
  • 98
  • Unnice but I guess it will work! What do I do if I do not just throw an exception but use the methods fail() and assertThat(), assert...(). Can I catch an exception thrown by a assertEqual() function? – Sebastian Hätälä May 22 '13 at 11:59
  • 1
    @user2407819 yes you can catch `AssertionError` but the above code would be sufficient since `Throwable` is a super class of `AssertionError`. – Marco Forberg May 22 '13 at 12:21
  • Truly unnice, but there is the Rule route it is just more complicated. – John B May 22 '13 at 14:25