Search code examples
testingjunittraceteardown

JUnit - Access failure messages in tearDown()


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


Solution

  • 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.