com.google.common.testing.junit4
Class TearDownTestCase

java.lang.Object
  extended by com.google.common.testing.junit4.TearDownTestCase
All Implemented Interfaces:
TearDownAccepter

public abstract class TearDownTestCase
extends java.lang.Object
implements TearDownAccepter

A base class for test cases that want to be able to register "tear-down" operations programatically -- i.e. when the static nature of Afters is not a good fit. E.g. say this following test case where one of the tests opens a File:

 @Test
 public void fileReading() {
   File file = new File("foo.txt");
   //.. the rest of the test
 }
 

If "file" is closed inside the test, and the test fails, this code is never executed. But to use @After, the code would have to be changed to:

 private File file;
 
 @Test
 public void fileReading() {
   file = new File("foo.txt");
   //.. the rest of the test
 }
 
 @After
 public void maybeCloseFile() throws Exception {
   if (file != null) {
     file.close();
     file = null;
   }
 }
 

There are several problems with the test above:

Using a TearDownTestCase, though, would make that be:

 @Test
 public void fileReading() {
   final File file = new File("foo.txt");
   addTearDown(new TearDown() {
     public void tearDown() throws Exception {
       file.close();
     }
   });
   //.. the rest of the test
 }
 

 

If you are writing a piece of test infrastructure, not a test case, and you want to be sure that what you do will be cleaned up, simply require your caller to pass in an active instance of TearDownAccepter, to which you can add your TearDowns.

Please see usage examples in TearDownTestCaseTest.

This class is the JUnit4 equivalent of TearDownTestCase.

Note that this class is a thin wrapper around the TearDownMethodRule. If you would rather not extend this class, simply add that an @Rule to your test class.

Author:
Luiz-Otavio Zorzella, Kevin Bourrillion

Field Summary
 TearDownMethodRule tearDownRule
           
 
Constructor Summary
TearDownTestCase()
           
 
Method Summary
 void addTearDown(TearDown tearDown)
          Registers a TearDown implementor which will be run after the test execution.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

tearDownRule

public final TearDownMethodRule tearDownRule
Constructor Detail

TearDownTestCase

public TearDownTestCase()
Method Detail

addTearDown

public final void addTearDown(TearDown tearDown)
Registers a TearDown implementor which will be run after the test execution.

Specified by:
addTearDown in interface TearDownAccepter


Copyright © 2010 Google. All Rights Reserved.