The Artima Developer Community
Sponsored Link

Java Buzz Forum
Global setUp() and tearDown() in JUnit tests

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Simon Brown

Posts: 636
Nickname: simonbrown
Registered: Jun, 2003

Simon Brown is a Java developer, architect and author.
Global setUp() and tearDown() in JUnit tests Posted: Apr 16, 2004 5:08 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Simon Brown.
Original Post: Global setUp() and tearDown() in JUnit tests
Feed Title: Simon Brown's weblog
Feed URL: http://www.simongbrown.com/blog/feed.xml?flavor=rss20&category=java
Feed Description: My thoughts on Java, software development and technology.
Latest Java Buzz Posts
Latest Java Buzz Posts by Simon Brown
Latest Posts From Simon Brown's weblog

Advertisement

Like many people, I want a way to run some one-time set up and tear down logic and the approach I usually take is to drop some code into a static initializer block in an abstract test case. For example...

public abstract class SomeTestCase extends TestCase {

  static {
    // perform the "global" set up logic
  }

}

Providing that I remember to subclass SomeTestCase then this approach works well. So that's set up covered, but what about tear down? Simple - just use a JVM shutdown hook.

public abstract class SomeTestCase extends TestCase {

  static {
    // perform the "global" set up logic

    // and now register the shutdown hook for tear down logic
    Runtime.getRuntime().addShutdownHook(new SomeTestCaseShutdownHook());
  }

}

This is quite a simple solution and is an alternative to the TestSetup class. As an example, I use it for creating a file structure on disk prior to running some tests and deleting that structure when the tests have run. The only caveat with this solution is that when you run your unit tests through Ant, the Ant ClassLoader executes the static initializer (and resets static variables) more than once. I don't know quite why it does this but if your global set up and tear down logic can safely be run more than once then it's not too much of a problem. Incidentally, this technique runs really well with the IntelliJ JUnit runner.

Read: Global setUp() and tearDown() in JUnit tests

Topic: Jen Chapin Previous Topic   Next Topic Topic: Community Access to the Jini Starter Kit Codebase

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use