Before and after methods for testcases

  Status: implemented,  Tue Jan 8 12:13:50 2008
  • Created: 2008-01-05 20:45:28+0100
  • Categories: unittest
  • Author: friebe

Scope of Change

There will be a way to run methods prior to and after all tests in a TestCase class. In contrast to setUp() and tearDown() they will be run only once per class and not once per test.


Rationale

Initialize and dispose of resources that are expensive to create, e.g. a server instance, a network connection, ...

Functionality



Note

This can violate the principle that unittest should be independent. For
some cases though this might be a necessary optimization to meet the 
goal that unittests should run fast - for other situations, setUp() and
tearDown() serve this purpose.

Annotations

The functionality can be used by annotating public static methods with the @beforeClass and @afterClass annotations.

Example

  class FtpIntegrationTest extends TestCase {
protected static $server= NULL;

#[@beforeClass]
public static function startServer() {
self::
$server= ...
self::
$server->start();
}

#[@test]
public function connect() {
$this->assertTrue(create(new FtpConnection('ftp://...'))->connect());
}

#[@afterClass]
public static function shutdownServer() {
self::
$server->shutdown();
}
}



Timeline

When a test suite is run, the following is performed for each test class added to the suite:

  * Call @beforeClass method if present
  * Then, for each method annotated with @test:
    * Call setUp() method
    * Call test method
    * Call tearDown() method
  * Call @afterClass method if present.

Definitions

  • The @beforeClass and @afterClass methods must be public static.
  • There may be one @beforeClass and one @afterClass method, not more.
  • When the @beforeClass method throws an exception, no further tests in that class are run (and instead marked as skipped).


Security considerations

n/a

Speed impact

Slightly slower because of additional checks.

Dependencies

none.

Related documents

- JUnit BeforeClass / AfterClass annotations: http://junit.sourceforge.net/javadoc_40/org/junit/BeforeClass.html http://junit.sourceforge.net/javadoc_40/org/junit/AfterClass.html

- TestNG annotations http://testng.org/doc/documentation-main.html#annotations

- Implementing patch http://xp-framework.net/rfc/contrib/rfc0150.diff

Comments



<EOF>


Table of contents