From: Mike C. <cla...@us...> - 2003-03-20 18:56:01
|
Update of /cvsroot/junit/junit/doc/faq In directory sc8-pr-cvs1:/tmp/cvs-serv23773 Modified Files: faq.htm Log Message: Added "How do I organize all test classes in a TestSuite automatically and not use or manage a TestSuite explicitly?" Index: faq.htm =================================================================== RCS file: /cvsroot/junit/junit/doc/faq/faq.htm,v retrieving revision 1.21 retrieving revision 1.22 diff -u -d -r1.21 -r1.22 --- faq.htm 28 Feb 2003 22:13:37 -0000 1.21 +++ faq.htm 20 Mar 2003 18:55:54 -0000 1.22 @@ -1 +1 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <title>JUnit FAQ</title> <meta http-equiv=Content-Type content="text/html; charset=iso-8859-1"> </head> <body> <h1><font color=#33ff33>J</font><font color=#cc0000>U</font>nit FAQ</h1> </p> <p></p> <hr size="1"> <!-- Summary --> <i> <p> JUnit is an open source Java testing framework used to write and run repeatable tests. <p> It is an instance of the xUnit architecture for unit testing frameworks. </i> <hr size="1"> <p> Maintained by <a href="mailto:mi...@cl...">Mike Clark</a> </p> <p> Last modified on February 28, 2003 </p> <hr> <br> <!-- Table Of Contents --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td> <b><font color="#000000" size="+1"> <a name="toc">Table of Contents:</a> </font></b> </td> </tr> </table> <ol> <li><b><a href="#faqinfo">FAQ Info:</a></b> <ol> <li><a href="#faqinfo_1">Who is responsible for this FAQ?</a></li> <li><a href="#faqinfo_2">How can I contribute to this FAQ?</a></li> <li><a href="#faqinfo_3">Where do I get the latest version of this FAQ?</a></li> </ol> </li> <p> <li><b><a href="#overview">Overview:</a></b> <ol> <li><a href="#overview_1">What is JUnit?</a></li> <li><a href="#overview_2">Where is the JUnit home page?</a></li> <li><a href="#overview_3">Where are the JUnit mailing lists and forums?</a></li> <li><a href="#overview_4">Where is the JUnit documentation?</a></li> <li><a href="#overview_5">Where can I find articles on JUnit?</a></li> <li><a href="#overview_6">What's the latest news on JUnit?</a></li> <li><a href="#overview_7">How is JUnit licensed?</a></li> <li><a href="#overview_8">What awards has JUnit won?</a></li> </ol> </li> <p> <li><b><a href="#started">Getting Started:</a></b> <ol> <li><a href="#started_1">Where do I download JUnit?</a></li> <li><a href="#started_2">How do I install JUnit?</a></li> <li><a href="#started_3">How do I uninstall JUnit?</a></li> <li><a href="#started_4">How do I ask questions?</a></li> <li><a href="#started_5">How do I submit bugs, patches, or feature requests?</a></li> </ol> </li> <p> <li><b><a href="#tests">Writing Tests:</a></b> <ol> <li><a href="#tests_1">How do I write and run a simple test?</a></li> <li><a href="#tests_2">How do I use a test fixture?</a></li> <li><a href="#tests_3">Why isn't my test fixture being run?</a></li> <li><a href="#tests_4">How do I test a method that doesn't return anything?</a></li> <li><a href="#tests_5">Under what conditions should I test get() and set() methods?</a></li> <li><a href="#tests_6">Under what conditions should I not test get() and set() methods?</a></li> <li><a href="#tests_7">How do I write a test that passes when an expected exception is thrown?</a></li> <li><a href="#tests_8">How do I write a test that fails when an unexpected exception is thrown?</a></li> <li><a href="#tests_9">What's the difference between a failure and an error?</a></li> <li><a href="#tests_10">How do I test protected methods?</a></li> <li><a href="#tests_11">How do I test private methods?</a></li> <li><a href="#tests_12">Why does JUnit only report the first failure in a single test?</a></li> <li><a href="#tests_13">In Java 1.4, 'assert' is a keyword. Won't this conflict with JUnit's assert() method?</a></li> <li><a href="#tests_14">How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?</a></li> <li><a href="#tests_15">Do I need to write a TestCase class for every class I need to test?</a></li> <li><a href="#tests_16">Is there a basic template I can use to create a test?</a></li> </ol> </li> <p> <li><b><a href="#organize">Organizing Tests:</a></b> <ol> <li><a href="#organize_1">Where should I put my test files?</a></li> <li><a href="#organize_2">How do I write a test suite for all of my tests?</a></li> <li><a href="#organize_3">How can I run setUp() and tearDown() code once for all of my tests?</a></li> </ol> </li> <p> <li><b><a href="#running">Running Tests:</a></b> <ol> <li><a href="#running_1">What CLASSPATH settings are needed to run JUnit?</a> </li> <li><a href="#running_2">Why do I get a NoClassDefFoundError when trying to test JUnit or run the samples?</a> </li> <li><a href="#running_3">How do I run the JUnit GUI test runner?</a> </li> <li><a href="#running_4">How do I run JUnit from my command window?</a> </li> <li><a href="#running_5">How do I run JUnit using Ant?</a> </li> <li><a href="#running_6">How do I use Ant to create HTML test reports?</a> </li> <li><a href="#running_7">How do I pass command-line arguments to a test execution?</a> </li> <li><a href="#running_8">Why do I get an error (ClassCastException or LinkageError) using the GUI TestRunners?</a> </li> <li><a href="#running_9">Why do I get a LinkageError when using XML interfaces in my TestCase?</a> </li> <li><a href="#running_10">Why do I get a ClassCastException when I use narrow() in an EJB client TestCase?</a> </li> <li><a href="#running_11">Why do I get the warning "AssertionFailedError: No tests found in XXX" when I run my test?</a> </li> <li><a href="#running_12">Why do I see "Unknown Source" in the stack trace of a test failure, rather than the source file's line number?</a> </li> <li><a href="#running_13">Why does the "excluded.properties" trick not work when running JUnit's GUI from inside my favorite IDE?</a> </li> <li><a href="#running_14">How do I get one test suite to invoke another?</a> </li> </ol> </li> <p> <li><b><a href="#best">Best Practices:</a></b> <ol> <li><a href="#best_1">When should tests be written?</a></li> <li><a href="#best_2">Do I have to write a test for everything?</a></li> <li><a href="#best_3">How simple is 'too simple to break'?</a></li> <li><a href="#best_4">How often should I run my tests?</a></li> <li><a href="#best_5">What do I do when a defect is reported?</a></li> <li><a href="#best_6">Why not just use System.out.println()?</a></li> <li><a href="#best_7">Why not just use a debugger?</a></li> </ol> </li> <p> <li><b><a href="#extend">Extending JUnit:</a></b> <ol> <li><a href="#extend_1">How do I extend JUnit?</a></li> <li><a href="#extend_2">What kinds of extensions are available?</a></li> </ol> </li> <p> <li><b><a href="#misc">Miscellaneous:</a></b> <ol> <li><a href="#misc_1">How do I integrate JUnit with my IDE?</a></li> <li><a href="#misc_2">How do I launch a debugger when a test fails?</a></li> <li><a href="#misc_3">Where can I find unit testing frameworks similar to JUnit for other languages?</a></li> </ol> </li> </ol> <!-- FAQ Info --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td align="left" width="90%"> <a name="faqinfo"><b><font size="+1">FAQ Info:</font></b></a> </td> <td align="right"> <a href="#toc">top</a> </td> </tr> </table> <ol> <li><b><a name="faqinfo_1">Who is responsible for this FAQ?</a></b> <p> The current version of this FAQ is maintained by <a href="mailto:mi...@cl...">Mike Clark</a>. <p> Most of the wisdom contained in this FAQ comes from the collective insights and hard-won experiences of the many good folks who participate on the JUnit mailing list and the JUnit community at large. <p> If you see your genius represented anywhere in this FAQ without due credit to you, please send me an email and I'll make things right. <p></p> <hr size="1"> </li> <li><b><a name="faqinfo_2">How can I contribute to this FAQ?</a></b> <p> Your contributions to this FAQ are greatly appreciated! The JUnit community thanks you in advance. <p> To contribute to this FAQ, simply write a JUnit-related question and answer, then send the unformatted text to <a href="mailto:mi...@cl...">Mike Clark</a>. Corrections to this FAQ are always appreciated, as well. <p> No reasonable contribution will be denied. Your name will always appear along with any contribution you make. <p></p> <hr size="1"> </li> <li><b><a name="faqinfo_3">Whe re do I get the latest version of this FAQ?</a></b> <p> The master copy of this FAQ is available at <a href="http://junit.sourceforge.net/doc/faq/faq.htm">http://junit.sourceforge.net/doc/faq/faq.htm</a>. <p> The entries in this FAQ are also documented in the <a href="http://www.jguru.com/faq/JUnit">jGuru FAQ</a>. <p> The JUnit distribution also includes this FAQ in the <code>doc</code> directory. <p></p> <hr size="1"> </li> </ol> <!-- Overview --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td align="left" width="90%"> <a name="overview"><b><font size="+1">Overview:</font></b></a> </td> <td align="right"> <a href="#toc">top</a> </td> </tr> </table> <ol> <li><b><a name="overview_1">What is JUnit?</a></b> <p> JUnit is an open source Java testing framework used to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. <p> JUnit features include: <ul> <li>Assertions for testing expected results</li> <li>Test fixtures for sharing common test data</li> <li>Test suites for easily organizing and running tests</li> <li>Graphical and textual test runners</li> </ul> <p> JUnit was originally written by Erich Gamma and Kent Beck. <p></p> <hr size="1"> </li> <li><b><a name="overview_2">Where is the JUnit home page?</a></b> <p> The official JUnit home page is <a href="http://junit.org">http://junit.org</a>. <p></p> <hr size="1"> </li> <li><b><a name="overview_3">Where are the JUnit mailing lists and forums?</a></b> <p> There are 3 mailing lists dedicated to everything JUnit: <ul> <li><a href="http://lists.sourceforge.net/lists/listinfo/junit-announce">JUnit announcements</a></li> <li><a href="http://groups.yahoo.com/group/junit/">JUnit user list</a></li> <li><a href="http://lists.sourceforge.net/lists/listinfo/junit-devel">JUnit developer list</a></li> </ul> <p> You can <a href="http://groups.yahoo.com/group/junit/">search</a> the JUnit user list archives for answers to frequently asked questions not included here. <p> There is also a <a href="http://www.jguru.com/forums/home.jsp?topic=JUnit">jGuru discussion forum</a> dedicated to everything JUnit. <p></p> <hr size="1"> </li> <li><b><a name="overview_4">Where is the JUnit documentation?</a></b> <p> The following documents are included in the JUnit distribution in the <code>doc</code> directory: <ul> <li><a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">JUnit Test Infected: Programmers Love Writing Tests</a></li> <li><a href="http://junit.sourceforge.net/doc/cookbook/cookbook.htm">JUnit Cookbook</a></li> <li><a href="http://junit.sourceforge.net/doc/cookstour/cookstour.htm">JUnit - A Cook's Tour</a></li> <li><a href="http://junit.sourceforge.net/doc/faq/faq.htm">JUnit FAQ</a></li> </ul> <p></p> <hr size="1"> </li> <li><b><a name="overview_5">Where can I find articles on JUnit?</a></b> <p> The JUnit home page maintains a list of <a href="http://www.junit.org/news/article/index.htm">JUnit articles</a>. <p></p> <hr size="1"> </li> <li><b><a name="overview_6">What's the latest news on JUnit?</a></b> <p> The JUnit home page publishes the <a href="http://www.junit.org/news/index.htm">latest JUnit news</a>. <p></p> <hr size="1"> </li> <li><b><a name="overview_7">How is JUnit licensed?</a></b> <p> JUnit is <a href="http://www.opensource.org/">Open Source Software</a>, released under <a href="http://oss.software.ibm.com/developerworks/oss/license-cpl.html">IBM's Common Public License Version 0.5</a> and hosted on <a href="http://sourceforge.net/projects/junit/">SourceForge</a>. <p></p> <hr size="1"> </li> <li><b><a name="overview_8">What awards has JUnit won?</a></b> <p> <ul> <li> <a href="http://www.javaworld.com/javaworld/jw-03-2002/jw-0326-awards.html">2002 JavaWorld Editors' Choice Awards (ECA)</a> <p> Best Java Performance Monitoring/Testing Tool </li> <li> <a href="http://www.javaworld.com/javaworld/jw-06-2001/j1-01-awards.html">2001 JavaWorld Editors' Choice Awards (ECA)</a> <p> Best Java Performance Monitoring/Testing Tool </li> </ul> <p></p> <hr size="1"> </li> </ol> <!-- Getting Started --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td align="left" width="90%"> <a name="started"><b><font size="+1">Getting Started:</font></b></a> </td> <td align="right"> <a href="#toc">top</a> </td> </tr> </table> <ol> <li><b><a name="started_1">Where do I download JUnit?</a></b> <p> The latest version of JUnit is available at <a href="http://download.sourceforge.net/junit/">http://download.sourceforge.net/junit/</a>. <p></p> <hr size="1"> </li> <li><b><a name="started_2">How do I install JUnit?</a></b> <p> <ol> <li> First, <a href="http://download.sourceforge.net/junit/">download</a> the latest version of JUnit, referred to below as <code>junit.zip</code>. </li> <br><br> <li> Then install JUnit on your platform of choice: <p> <u>Windows</u> <p> To install JUnit on Windows, follow these steps: <p> <ol> <li>Unzip the <code>junit.zip</code> distribution file to a directory referred to as <code>%JUNIT_HOME%</code>. </li> <p> <li>Add JUnit to the classpath: <p> <code>set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar</code> </li> </ol> <p> <u>Unix (bash)</u> <p> To install JUnit on Unix, follow these steps: <p> <ol> <li>Unzip the <code>junit.zip</code> distribution file to a directory referred to as <code>$JUNIT_HOME</code>. </li> <p> <li>Add JUnit to the classpath: <p> <code>export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar</code> </li> </ol> </li> <br> <li> <i>(Optional)</i> Unzip the <code>$JUNIT_HOME/src.jar</code> file. </li> <br><br> <li> Test the installation by using either the textual or graphical test runner to run the sample tests distributed with JUnit. <p> <i>Note: The sample tests are not contained in the <code>junit.jar</code>, but in the installation directory directly. Therefore, make sure that the JUnit installation directory is in the CLASSPATH.</i> <p> For the textual TestRunner, type: <p> <blockquote><pre> java junit.textui.TestRunner junit.samples.AllTests </pre></blockquote> <p> For the graphical TestRunner, type: <p> <blockquote><pre> java junit.swingui.TestRunner junit.samples.AllTests </pre></blockquote> <p> All the tests should pass with an "OK" (textual) or a green bar (graphical). <p> If the tests don't pass, verify that <code>junit.jar</code> is in the CLASSPATH. </li> <br><br> <li> Finally, <a href="#overview_4">read</a> the documentation. </li> </ol> <p></p> <hr size="1"> </li> <li><b><a name="started_3">How do I uninstall JUnit?</a></b> <p> <ol> <li>Delete the directory structure where you unzipped the JUnit distribution </li> <br> <li>Remove <code>junit.jar</code> from the classpath </li> </ol> <p> JUnit does not modify the registry so simply removing all the files will fully uninstall it. <p></p> <hr size="1"> </li> <li><b><a name="started_4">How do I ask questions?</a></b> <p> Questions that are not answered in the <a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a> or in the <a href="#overview_4">documentation</a> should be posted to the <a href="http://www.jguru.com/forums/home.jsp?topic=JUnit">jGuru discussion forum</a> or the <a href="http://groups.yahoo.com/group/junit/">JUnit user mailing list</a>. </p> <p> Please stick to technical issues on the discussion forum and mailing lists. Keep in mind that these are public, so do <b>not</b> include any confidental information in your questions! <p> You should also read <a href="http://www.tuxedo.org/%7Eesr/faqs/smart-questions.html">"How to ask questions the smart way"</a> by Eric Raymond before participating in the discussion forum and mailing lists. <p> <i> NOTE: <br> Please do NOT submit bugs, patches, or feature requests to the discussion forum or mailing lists. <br> Refer instead to <a href="#started_5">"How do I submit bugs, patches, or feature requests?"</a>. </i> <p></p> <hr size="1"> </li> <li><b><a name="started_5">How do I submit bugs, patches, or feature requests?</a></b> <p> JUnit celebrates programmers testing their own software. In this spirit, bugs, patches, and feature requests that include JUnit tests have a better chance of being addressed than those without. <p> JUnit is forged on <a href="http://sourceforge.net/projects/junit">SourceForge</a>. Please use the tools provided by SourceForge for your submissions. <p></p> <hr size="1"> </li> </ol> <!-- Writing Tests --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td align="left" width="90%"> <a name="tests"><b><font size="+1">Writing Tests:</font></b></a> </td> <td align="right"> <a href="#toc">top</a> </td> </tr> </table> <ol> <li><b><a name="tests_1"></a>How do I write and run a simple test?</b> <p> <ol> <li>Create a subclass of <code>TestCase</code>: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> package junitfaq; import java.util.*; import junit.framework.*; public class SimpleTest extends TestCase { public SimpleTest(String name) { super(name); } </pre></table> </li> <br> <li>Write a test method to assert expected results on the object under test: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> public void testEmptyCollection() { Collection collection = new ArrayList(); assertTrue(collection.isEmpty()); } </pre></table> </li> <br> <li>Write a <code>suite()</code> method that uses reflection to dynamically create a test suite containing all the <code>testXXX()</code> methods: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> public static Test suite() { return new TestSuite(SimpleTest.class); } </pre></table> </li> <br> <li>Write a <code>main()</code> method to conveniently run the test with the textual test runner: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } } </pre></table> </li> <br> <li>Run the test: <p> <ul> <li> To run the test with the textual test runner used in <code>main()</code>, type: <p> <blockquote><pre> java junitfaq.SimpleTest </pre></blockquote> <p> The passing test results in the following textual output: <p> <blockquote><pre> . Time: 0 OK (1 tests) </pre></blockquote> <br> <li> To run the test with the graphical test runner, type: <p> <blockquote><pre> java junit.swingui.TestRunner junitfaq.SimpleTest </pre></blockquote> <p> The passing test results in a green bar displayed in the graphical UI. </ul> </li> </ol> <p></p> <hr size="1"> </li> <li><b><a name="tests_2"></a>How do I use a test fixture?</b> <p> A test fixture is useful if you have two or more tests for a common set of objects. Using a test fixture avoids duplicating the test code necessary to initialize and cleanup those common objects for each test. <p> Tests can share the objects in a test fixture, with each test invoking different methods on the objects in the fixture and asserting different expected results. Each test runs in its own test fixture to isolate tests from the changes made by other tests. Because the tests are isolated, they can be run in any order. <p> To create a test fixture, define a <code>setUp()</code> method that initializes common objects and a <code>tearDown()</code> method to cleanup those objects. The JUnit framework automatically invokes the <code>setUp()</code> method before each test is run and the <code>tearDown()</code> method after each test is run. <p> The following test uses a test fixture to initialize and cleanup a common <code>Collection</code> object such that both tests are isolated from changes made by the other: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> package junitfaq; import junit.framework.*; import java.util.*; public class SimpleTest extends TestCase { private Collection _collection; public SimpleTest(String name) { super(name); } protected void setUp() { _collection = new ArrayList(); } protected void tearDown() { _collection.clear(); } public void testEmptyCollection() { assertTrue(_collection.isEmpty()); } public void testOneItemCollection() { _collection.add("itemA"); assertEquals(1, _collection.size()); } } </pre></table> <p></p> <hr size="1"> </li> <li><b><a name="tests_3"></a>Why isn't my test fixture being run?</b> <p> Make sure the test fixture methods are defined as follows, noting that both method names are case sensitive: <p> <blockquote><pre> protected void setUp() { // initialization code } protected void tearDown() { // cleanup code } </pre></blockquote> <p></p> <hr size="1"> </li> <li><b><a name="tests_4"></a>How do I test a method that doesn't return anything?</b> <p> <i>(Submitted by: Dave Astels)</i> <p> Often if a method doesn't return a value, it will have some side effect. Actually, if it doesn't return a value AND doesn't have a side effect, it isn't doing anything. <p> There may be a way to verify that the side effect actually occurred as expected. For example, consider the <code>add()</code> method in the Collection classes. There are ways of verifying that the side effect happened (i.e. the object was added). You can check the size and assert that it is what is expected: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> public void testCollectionAdd() { Collection collection = new ArrayList(); assertEquals(0, collection.size()); collection.add("itemA"); assertEquals(1, collection.size()); collection.add("itemB"); assertEquals(2, collection.size()); } </pre></table> <p> Another approach is to make use of <a href="http://www.mockobjects.com">MockObjects</a>. <p> A related issue is to design for testing. For example, if you have a method that is meant to output to a file, don't pass in a filename, or even a <code>FileWriter</code>. Instead, pass in a <code>Writer</code>. That way you can pass in a <code>StringWriter</code> to capture the output for testing purposes. Then you can add a method (e.g. <code>writeToFileNamed(String filename)</code>) to encapsulate the <code>FileWriter</code> creation. <p></p> <hr size="1"> </li> <li><b><a name="tests_5"></a>Under what conditions should I test get() and set() methods?</b> <p> Unit tests are intended to alleviate fear that something might break. If you think a <code>get()</code> or <code>set()</code> method could reasonably break, or has in fact contributed to a defect, then by all means write a test. <p> In short, test until you're confident. What you choose to test is subjective, based on your experiences and confidence level. Remember to be practical and maximize your testing investment. <p> Refer also to <a href="#best_3">"How simple is 'too simple to break'?"</a>. <p></p> <hr size="1"> </li> <li><b><a name="tests_6"></a>Under what conditions should I not test get() and set() methods?</b> <p> <i>(Submitted by: J. B. Rainsberger)</i> <p> Most of the time, get/set methods just can't break, and if they can't break, then why test them? While it is usually better to test more, there is a definite curve of diminishing returns on test effort versus "code coverage". Remember the maxim: "Test until fear turns to boredom." <p> Assume that the <code>getX()</code> method only does "return x;" and that the <code>setX()</code> method only does "this.x = x;". If you write this test: <blockquote><pre> testGetSetX() { setX(23); assertEquals(23, getX()); } </pre></blockquote> then you are testing the equivalent of the following: <blockquote><pre> testGetSetX() { x = 23; assertEquals(23, x); } </pre></blockquote> or, if you prefer, <blockquote><pre> testGetSetX() { assertEquals(23, 23); } </pre></blockquote> At this point, you are testing the Java compiler, or possibly the interpreter, and not your component or application. There is generally no need for you to do Java's testing for them. <p> If you are concerned about whether a property has already been set at the point you wish to call <code>getX()</code>, then you want to test the constructo r, and not the <code>getX()</code> method. This kind of test is especially useful if you have multiple constructors: <blockquote><pre> testCreate() { assertEquals(23, new MyClass(23).getX()); } </pre></blockquote> <p></p> <hr size="1"> </li> <li><b><a name="tests_7"></a>How do I write a test that passes when an expected exception is thrown?</b> <p> Catch the exception within the test method. If it isn't thrown, call the <code>fail()</code> method to signal the failure of the test. <p> The following is an example test that passes when the expected <code>IndexOutOfBoundsException</code> is raised: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td> <pre> public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); try { Object o = emptyList.get(0); fail("Should raise an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException success) {} } </pre></table> <p></p> <hr size="1"> </li> <li><b><a name="tests_8"></a>How do I write a test that fails when an unexpected exception is thrown?</b> <p> Declare the exception in the <code>throws</code> clause of the test method and don't catch the exception within the test method. Uncaught exceptions will cause the test to fail with an error. <p> The following is an example test that fails when the <code>IndexOutOfBoundsException</code> is raised: <p> <table><tr><td bgcolor="#cc0000"> </td><td> </td><td> <pre> public void testIndexOutOfBoundsExceptionNotRaised() throws IndexOutOfBoundsException { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } </pre></table> <p></p> <hr size="1"> </li> <li><b><a name="tests_9"></a>What's the difference between a failure and an error?</b> <p> Assertions are used to check for the possibility of failures, therefore failures are anticipated. Errors are unanticipated problems resulting in uncaught exceptions being propagated from a JUnit test method. <p> In the following example, the <code>FileNotFoundException</code> is expected and checked with an assertion. If the expected exception is not raised, then a failure is produced. If any other unexpected <code>IOException</code> or unchecked exception (e.g. <code>NullPointerException</code>) is raised, the JUnit framework catches the exception and signals an error. <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td> <pre> public void testNonexistentFileRead() throws IOException { try { File file = new File("doesNotExist.txt"); FileReader reader = new FileReader(file); assertEquals('a', (char)reader.read()); fail("Read from a nonexistent file?!"); } catch (FileNotFoundException success) {} } </pre></table> <p> In the following example, an <code>IOException</code> is not expected. The JUnit framework will signal an error if an <code>IOException</code> (e.g. <code>FileNotFoundException</code>) or any unchecked exception (e.g. <code>NullPointerException</code>) is raised. <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td> <pre> public void testExistingFileRead() throws IOException { // exists.txt created in setup(), perhaps File file = new File("exists.txt"); FileReader reader = new FileReader(file); assertEquals('a', (char)reader.read()); } </pre></table> <p> Both failures and errors will cause the test to fail. However, it is useful to differentiate between failures and errors because the debugging process is slightly different. <p> In the first example, the use of <code>fail()</code> will not generate a complete stack trace including the method that raised the exception. In this case that's sufficient since we anticipate that the exception will be raised. If it's not raised, then it's a problem with the test itself. <p> In the second example, the JUnit framework catches the exception and generates an error with a complete stack trace for the exception. Since we don't expect this exception to be raised, a complete stack trace is useful in debugging why it was raised. <p></p> <hr size="1"> </li> <li><b><a name="tests_10"></a>How do I test protected methods?</b> <p> Place your tests in the same package as the classes under test. <p> Refer to <a href="#organize_1">"Where should I put my test files?"</a> for examples of how to organize tests for protected method access. <p></p> <hr size="1"> </li> <li><b><a name="tests_11"></a>How do I test private methods?</b> <p> Testing private methods may be an indication that those methods should be moved into another class to promote reusability. <p> But if you must... <p> You can use reflection to subvert the access control mechanism. If you are using JDK 1.3 or higher you can use the <a href="http://groups.yahoo.com/group/junit/files/src/PrivilegedAccessor.java">PrivilegedAccessor</a> class. Examples of how to use this class are available in <a href="http://groups.yahoo.com/group/junit/files/src/PrivilegedAccessorTest.java">PrivilegedAccessorTest</a>. <p></p> <hr size="1"> </li> <li><b><a name="tests_12"></a>Why does JUnit only report the first failure in a single test?</b> <p> <i>(Submitted by: J. B. Rainsberger)</i> <p> Reporting multiple failures in a single test is generally a sign that the test does too much, compared to what a unit test ought to do. Usually this means either that the test is really a functional/acceptance/customer test or, if it is a unit test, then it is too big a unit test. <p> JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test. Shared setup code is most natural when sharing between tests. This is a design decision that permeates JUnit, and when you decide to report multiple failures per test, you begin to fight against JUnit. This is not recommended. <p> Long tests are a design smell and indicate the likelihood of a design problem. Kent Beck is fond of saying in this case that "there is an opportunity to learn something about your design." We would like to see a pattern language develop around these problems, but it has not yet been written down. <p> Finally, note that a single test with multiple assertions is isomorphic to a test case with multiple tests: <p> One test method, three assertions: <p> <blockquote><pre> public class MyTestCase extends TestCase { public void testSomething() { // Set up for the test, manipulating local variables assertTrue(condition1); assertTrue(condition2); assertTrue(condition3); } } </pre></blockquote> <p> Three test methods, one assertion each: <p> <blockquote><pre> public class MyTestCase extends TestCase { // Locale variables become instance variables protected void setUp() { // Set up for the test, manipulating instance variables } public void testCondition1() { assertTrue(condition1); } public void testCondition2() { assertTrue(condition2); } public void testCondition3() { assertTrue(condition3); } } </pre></blockquote> The resulting tests use JUnit's natural execution and reporting mechanism and, failure in one test does not affect the execution of the other tests. You generally want exactly one test to fail for any given bug, if you can manage it. <p></p> <hr size="1"> </li> <li><b><a name="tests_13"></a>In Java 1.4, 'assert' is a keyword. Won't this conflict with JUnit's <code>assert()</code> method?</b> <p> <i>(Submitted by: David Stagner)</i> <p> JUnit 3.7 deprecated <code>assert()</code> and replaced it with <code>assertTrue()</code>, which works exactly the same way. <p> Simply upgrade your JUnit to version 3.7 or higher and change all <code>assert()</code> calls in your existing tests to <code>assertTrue()</code>. <p></p> <hr size="1"> </li> <li><b><a name="tests_14"></a>How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?</b> <p> Refactoring J2EE components to delegate functionality to other objects that don't have to be run in a J2EE container will improve t he design and testability of the software. <p> <a href="http://jakarta.apache.org/cactus/index.html">Cactus</a> is an open source JUnit extension that can be used to test J2EE components in their natural environment. <p></p> <hr size="1"> </li> <li><b><a name="tests_15"></a>Do I need to write a <code>TestCase</code> class for every class I need to test?</b> <p> <i>(Submitted by: J. B. Rainsberger)</i> <p> No. It is a convention to start with one <code>TestCase</code> class per class under test, but it is not necessary. <p> <code>TestCase</code> classes only provide a way to organize tests, nothing more. Generally you will start with one <code>TestCase</code> class per class under test, but then you may find that a small group of tests belong together with their own common test fixture.[1] In this case, you may move those tests to a new <code>TestCase</code> object. This is a simple object-oriented refactoring: separating responsibilities of an object that does too much. <p> Another point to consider is that the <code>TestSuite</code> is the smallest execution unit in JUnit: you cannot execute anything smaller than a TestSuite at one time without changing source code. In this case, you probably do not want to put tests in the same <code>TestCase</code> class unless they somehow "belong together". If you have two groups of tests that you think you'd like to execute separately from one another, it is wise to place them in separate <code>TestCase</code> classes. <p> <i> [1] A test fixture is a common set of test data and collaborating objects shared by many tests. Generally they are implemented as instance variables in the <code>TestCase</code> class. </i> <p></p> <hr size="1"> </li> <li><b><a name="tests_16"></a>Is there a basic template I can use to create a test?</b> <p> <i>(Submitted by: Eric Armstrong)</i> <p> The following templates are a good starting point. Copy/paste and edit these templates to suit your coding style. <p> SampleTest is a basic test template: <p> <blockquote><pre> import junit.framework.TestCase; public class SampleTest extends TestCase { private java.util.List emptyList; /** * Sets up the test fixture. * (Called before every test case method.) */ protected void setUp() { emptyList = new java.util.ArrayList(); } /** * Tears down the test fixture. * (Called after every test case method.) */ protected void tearDown() { emptyList = null; } public void testSomeBehavior() { assertEquals("Empty list should have 0 elements", 0, emptyList.size()); } public void testForException() { try { Object o = emptyList.get(0); fail("Should raise an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException success) { } } public static void main(String args[]) { junit.textui.TestRunner.run(SampleTest.class); } } </pre></blockquote> SampleTestSuite is a template for a suite of tests: <p> <blockquote><pre> import junit.framework.Test; import junit.framework.TestSuite; public class SampleTestSuite { public static Test suite() { TestSuite suite = new TestSuite("Sample Tests"); // // Add one entry for each test class // or test suite. // suite.addTestSuite(SampleTest.class); // // For a master test suite, use this pattern. // (Note that here, it's recursive!) // suite.addTest(AnotherTestSuite.suite()); return suite; } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } } </pre></blockquote> <p></p> <hr size="1"> </li> </ol> <!-- Organizing Tests --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td align="left" width="90%"> <a name="organize"><b><font size="+1">Organizing Tests:</font></b></a> </td> <td align="right"> <a href="#toc">top</a> </td> </tr> </table> <ol> <li><b><a name="organize_1"></a>Where should I put my test files?</b> <p> You can place your tests in the same package and directory as the classes under test. <p> For example: <blockquote><pre> src com xyz SomeClass.java SomeClassTest.java </pre></blockquote> <p> Or, if you feel this clutters the source directory, you can place the tests in a separate parallel directory structure with package alignment. <p> For example: <blockquote><pre> src com xyz SomeClass.java test com xyz SomeClassTest.java </pre></blockquote> <p> These approaches allow the tests to access to all the package visible methods and fields of the classes under test. <p></p> <hr size="1"> </li> <li><b><a name="organize_2"></a>How do I write a test suite for all of my tests?</b> <p> Write a <code>suite()</code> method that creates a <code>TestSuite</code> containing all your tests. <p> For example: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> import junit.framework.*; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(SomeTest.suite()); suite.addTest(AnotherTest.suite()); return suite; } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } } </pre></table> <p> Running <code>AllTests</code> will automatically run all of its contained tests in one fell swoop. <p> You can arbitrarily group any tests into test suites as appropriate by package, logical layers, test type, etc. <p></p> <hr size="1"> </li> <li><b><a name="organize_3"></a>How can I run setUp() and tearDown() code once for all of my tests?</b> <p> The desire to do this is usually a symptom of excessive coupling in your design. If two or more tests must share the same test fixture state, then the tests may be trying to tell you that the classes under test have some undesirable dependencies. <p> Refactoring the design to further decouple the classes under test and eliminate code duplication is usually a better investment than setting up a shared test fixture. <p> But if you must... <p> You can wrap the test suite containing all your tests in a subclass of <code>TestSetup</code> which invokes <code>setUp()</code> exactly once before all the tests are run and invokes <code>tearDown()</code> exactly once after all the tests have been run. <p> The following is an example <code>suite()</code> method that uses a <code>TestSetup</code> for one-time initialization and cleanup: <p> <table><tr><td bgcolor="#33ff33"> </td><td> </td><td><pre> import junit.framework.*; import junit.extensions.TestSetup; public class AllTestsOneTimeSetup { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(SomeTest.suite()); suite.addTest(AnotherTest.suite()); TestSetup wrapper = new TestSetup(suite) { protected void setUp() { oneTimeSetUp(); } protected void tearDown() { oneTimeTearDown(); } }; return wrapper; } public static void oneTimeSetUp() { // one-time initialization code } public static void oneTimeTearDown() { // one-time cleanup code } } </pre></table> <p></p> <hr size="1"> </li> </ol> <!-- Running Tests --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td align="left" width="90%"> <a name="running"><b><font size="+1">Running Tests:</font></b></a> </td> <td align="right"> <a href="#toc">top</a> </td> </tr> </table> <ol> <li><b><a name="running_1"></a>What CLASSPATH settings are needed to run JUnit?</b> <p> <i>(Submitted by: Eric Armstrong)</i> <p> To run your JUnit tests, you'll need the following elemements in your CLASSPATH: <ul> <li>JUnit class files <li>Your class files, including your JUnit test classes <li>Libraries your class files depend on </ul> </p> <p> If attempting to run your tests results in a <code >NoClassDefFoundError</code>, then something is missing from your CLASSPATH. </p> <p> <u>Windows Example:</u> </p> <p> <code>set CLASSPATH=%JUNIT_HOME%\junit.jar;c:\myproject\classes;c:\myproject\lib\something.jar</code> </p> <p> <u>Unix (bash) Example:</u> </p> <p> <code>export CLASSPATH=$JUNIT_HOME/junit.jar:/myproject/classes:/myproject/lib/something.jar</code> </p> <p></p> <hr size="1"> </li> <li><b><a name="running_2"></a>Why do I get a <code>NoClassDefFoundError</code> when trying to test JUnit or run the samples?</b> <p> <i>(Submitted by: J.B. Rainsberger and Jason Rogers)</i> <p> <p> Most likely your CLASSPATH doesn't include the JUnit installation directory. </p> <p> Refer to <a href="#running_1">"What CLASSPATH settings are needed to run JUnit?"</a> for more guidance. </p> <p> Also consider running <a href="http://www.clarkware.com/software/WhichJUnit.zip">WhichJunit</a> to print the absolute location of the JUnit class files required to run and test JUnit and its samples. <p> If the CLASSPATH seems mysterious, read <a href="http://java.sun.com/j2se/1.4/docs/tooldocs/findingclasses.html">this</a>! <p></p> <hr size="1"> </li> <li><b><a name="running_3"></a>How do I run the JUnit GUI test runner?</b> <p> <i>(Submitted by: Eric Armstrong)</i> <p> <ol> <li> <a href="#running_1">Set your CLASSPATH</a> </li> <br> <li>Invoke the runner: <br><br> <code> java junit.swingui.TestRunner <test class name> </code> </li> </ol> </p> <p></p> <hr size="1"> </li> <li><b><a name="running_4"></a>How do I run JUnit from my command window?</b> <p> <i>(Submitted by: Eric Armstrong)</i> <p> <ol> <li> <a href="#running_1">Set your CLASSPATH</a> </li> <br> <li>Invoke the runner: <br><br> <code> java junit.textui.TestRunner <test class name> </code> </li> </ol> </p> <p></p> <hr size="1"> </li> <li><b><a name="running_5"></a>How do I run JUnit using Ant?</b> <p> <i>(Submitted by: Eric Armstrong)</i> <p> <ol> <li> Define any necessary Ant properties: <blockquote><pre> <property name="src" value="./src" /> <property name="lib" value="./lib" /> <property name="classes" value="./classes" /> <property name="test.class.name" value="com.xyz.MyTestSuite" /> </pre></blockquote> </li> <br> <li>Set up the CLASSPATH to be used by JUnit: <blockquote><pre> <path id="test.classpath"> <pathelement location="${classes}" /> <pathelement location="/path/to/junit.jar" /> <fileset dir="${lib}"> <include name="**/*.jar"/> </fileset> </path> </pre></blockquote> </li> <br> <li>Define the Ant task for running JUnit: <blockquote><pre> <target name="test"> <junit fork="yes" haltonfailure="yes"> <test name="${test.class.name}" /> <formatter type="plain" usefile="false" /> <classpath refid="test.classpath" /> </junit> </target> </pre></blockquote> </li> <br> <li>Run the test: <blockquote><pre> ant test </pre></blockquote> </li> </ol> </p> <p> Refer to the <a href="http://jakarta.apache.org/ant/manual/OptionalTasks/junit.html">JUnit Ant Task</a> for more information. </p> <p></p> <hr size="1"> </li> <li><b><a name="running_6"></a>How do I use Ant to create HTML test reports?</b> <p> <i>(Submitted by: Eric Armstrong and Steffen Gemkow)</i> <p> <ol> <li> Ensure that Ant's <code>optional.jar</code> file is either in your CLASSPATH or exists in your <code>$ANT_HOME/lib</code> directory. </li> <br> <li> Add an ANT property for the directory containing the HTML reports: <blockquote><pre> <property name="test.reports" value="./reports" /> </pre></blockquote> </li> <br> <li>Define the Ant task for running JUnit and generating reports: <blockquote><pre> <target name="test-html"> <junit fork="yes" printsummary="no" haltonfailure="no"> <batchtest fork="yes" todir="${test.reports}" > <fileset dir="${classes}"> <include name="**/*Test.class" /> </fileset> </batchtest> <formatter type="xml" /> <classpath refid="test.classpath" /> </junit> <junitreport todir="${test.reports}"> <fileset dir="${test.reports}"> <include name="TEST-*.xml" /> </fileset> <report todir="${test.reports}" /> </junitreport> </target> </pre></blockquote> </li> <br> <li>Run the test: <blockquote><pre> ant test-html </pre></blockquote> </li> </ol> </p> <p> Refer to the <a href="http://jakarta.apache.org/ant/manual/OptionalTasks/junit.html">JUnit Ant Task</a> for more information. </p> <p></p> <hr size="1"> </li> <li><b><a name="running_7"></a>How do I pass command-line arguments to a test execution?</b> <p> Use the <tt>-D</tt> JVM command-line options, as in: <blockquote><pre> -DparameterName=parameterValue </pre></blockquote> </p> <p> If the number of parameters on the command line gets unweildy, pass in the location of a property file that defines a set of parameters. Alternatively, the <a href="http://junit-addons.sf.net">JUnit-addons package</a> contains the <tt>XMLPropertyManager</tt> and <tt>PropertyManager</tt> classes that allow you to define a property file (or XML file) containing test parameters. </p> <p></p> <hr size="1"> </li> <li><b><a name="running_8"></a>Why do I get an error (<code>ClassCastException</code> or <code>LinkageError</code>) using the GUI TestRunners?</b> <p> <i>(Submitted by: Scott Stirling)</i> <p> JUnits GUI TestRunners use a custom class loader (<code>junit.runner.TestCaseClassLoader</code>) to dynamically reload your code every time you press the "Run" button so you don't have to restart the GUI to reload your classes if you recompile them. The default classloaders of the Java Virtual Machine do not dynamically reload changed classes. But JUnits custom class loader finds and loads classes from the same CLASSPATH used by the JVMs system classloader. So, by design, it "sits in front of" the system loader and applies a filter to determine whether it should load a given class or delegate the loading of a class to the system classloader. This filter is configured with a list of String patterns in a properties file called <code>excluded.properties</code>. <p> The <code>excluded.properties</code> file contains a numbered list (<code>excluded.0</code>, <code>excluded.1</code>, <code>excluded.2</code>, etc.) of properties whose values are patterns for packages. This file is packaged in <code>junit.jar</code> as <code>junit/runner/excluded.properties</code>. As of JUnit 3.7 and Java 1.4, its contents are: <blockquote><pre> # # The list of excluded package paths for the TestCaseClassLoader # excluded.0=sun.* excluded.1=com.sun.* excluded.2=org.omg.* excluded.3=javax.* excluded.4=sunw.* excluded.5=java.* </pre></blockquote> <p> There are some conditions, discussed below, where the default exclusions are insufficient and you will want to add some more to this list and then either update the <code>junit.jar</code> file with your customized version or place your customized version in the CLASSPATH before <code>junit.jar</code>. <p></p> <hr size="1"> </li> <li><b><a name="running_9"></a>Why do I get a <code>LinkageError</code> when using XML interfaces in my TestCase?</b> <p> <i>(Submitted by: Scott Stirling)</i> <p> The workaround as of JUnit 3.7 is to add <code>org.w3c.dom.*</code> and <code>org.xml.sax.*</code> to your <code>excluded.properties</code>. <p> Its just a matter of time before this fix becomes incorporated into the released version of JUnit's <code>excluded.properties</code>, since JAXP is a standard part of JDK 1.4. It will be just like excluding <code>org.omg.*</code>. By the way, if you download the JUnit source from its Sourceforge CVS, you will find that these patterns have already been added to the default excluded.properties and so has a pattern for JINI. In fact, here is the current version in CVS, which demonstrates how to add exclusions to the list too: <blockquote><pre> # # The list of excluded package paths for the TestCaseClassLoader # excluded.0=sun.* excluded.1=com.sun.* excluded.2=org.omg.* exclu ded.3=javax.* excluded.4=sunw.* excluded.5=java.* excluded.6=org.w3c.dom.* excluded.7=org.xml.sax.* excluded.8=net.jini.* </pre></blockquote> <p> This is the most common case where the default <code>excluded.properties</code> list needs modification. The cause of the <code>LinkageError</code> is related to using JAXP in your test cases. By JAXP I mean the whole set of <code>javax.xml.*</code> classes and the supporting <code>org.w3c.dom.*</code> and <code>org.xml.sax.*</code> classes. <p> As stated above, the JUnit GUI TestRunners' classloader relies on the <code>excluded.properties</code> for classes it should delegate to the system classloader. JAXP is an unusual case because it is a standard Java extension library dependent on classes whose package names (<code>org.w3c.dom.*</code> and <code>org.xml.sax.*</code>) do not begin with a standard Java or Sun prefix. This is similar to the relationship between <code>javax.rmi.*</code> and the <code>org.omg.*</code> classes, which have been excluded by default in JUnits <code>excluded.properties</code> for a while. <p> What can happen, and frequently does when using the JUnit Swing or AWT UI with test cases that reference, use or depend on JAXP classes, such as Log4J, Apache SOAP, Axis, Cocoon, etc., is that the JUnit class loader (properly) delegates <code>javax.xml.*</code> classes it "sees" to the system loader. But then the system loader, in the process of initializing and loading that JAXP class, links and loads up a bunch of <code>org.w3c.dom</code>/<code>org.xml.sax</code> classes. When it does so, the JUnit custom classloader is not involved at all because the system classloader never delegates "down" or checks with custom classloaders to see if a class is already loaded. At any point after this, if the JUnit loader is asked to load an <code>org.w3c.dom</code>/<code>org.xml.sax</code> class that it's never seen before, it will try to load it because the classs name doesn't match any of the patterns in the default exclude list. Thats when a <code>LinkageError</code> occurs. This is really a flaw in the JUnit classloader design, but there is the workaround given above. <p> Java 2 JVMs keep classes (remember, classes and objects, though related, are different entities to the JVM - Im talking about classes here, not object instances) in namespaces, identifying them by their fully qualified classname plus the instance of their defining (not initiating) loader. The JVM will attempt to assign all unloaded classes referenced by an already defined and loaded class to that class's defining loader. The JVM's classresolver routine (implemented as a C function in the JVM source code) keeps track of all these class loading events and "sees" if another classloader (such as the JUnit custom loader) attempts to define a class that has already been defined by the system loader. According to the rules of Java 2 loader constraints, in case a class has already been defined by the system loader, any attempts to load a class should first be delegated to the system loader. A "proper" way for JUnit to handle this feature would be to load classes from a repository other than the CLASSPATH that the system classloader knows nothing about. And then the JUnit custom classloader could follow the standard Java 2 delegation model, which is to always delegate class loading to the system loader, and only attempt to load if that fails. Since they both load from the CLASSPATH in the current model, if the JUnit loader delegated like it's supposed to, it would never get to load any classes since the system loader would always find them. <p> You could try to hack around this in the JUnit source by catching the <code>LinkageError</code> in TestCaseClassLoader's <code>loadClass()</code> method and then making a recovery call to <code>findSystemClass()</code> -- thereby delegating to the system loader after the violation has been caught. But this hack only works some of the time, because now you can have the reverse problem where the JUnit loader will load a host of <code>org.w3c.dom</code>/<code>org.xml.sax</code> classes, and then the system loader violates the loader contraints at some point when it tries to do exactly what I described above with JAXP because it doesn't ever delegate to its logical child (the JUnit loader). Inevitably, if your test cases use many JAXP and related XML classes, one or the other classloader will end up violating the constraints whatever you do. <p></p> <hr size="1"> </li> <li><b><a name="running_10"></a>Why do I get a <code>ClassCastException</code> when I use <code>narrow()</code> in an EJB client TestCase?</b> <p> <i>(Submitted by: Scott Stirling)</i> <p> The solution is to prevent your EJB's interface classes from being loaded by the JUnit custom class loader by adding them to <code>excluded.properties</code>. <p> This is another problem inherent to JUnit's dynamically reloading TestCaseClassLoader. Similar to the LinkageErrors with JAXP and the <code>org.xml.sax</code> and <code>org.w3c.dom</code> classes, but with a different result. <p> Here's some example code: <blockquote><pre> Point point; PointHome pointHome; // The next line works in textui, but throws // ClassCastException in swingui pointHome = (PointHome)PortableRemoteObject. narrow(ctx.lookup("base/PointHome"), PointHome.class); </pre></blockquote> <p> When you call <code>InitialContext.lookup()</code>, it returns an object that was loaded and defined by the JVM's system classloader (<code>sun.misc.Launcher$AppClassLoader</code>), but the <code>PointEJBHome.class</code> type is loaded by JUnit's TestCaseClassLoader. In the <code>narrow()</code>, the two fully qualified class names are the same, but the defining classloaders for the two are different so you get the exception during the narrow because the JVM doesn't see them as being the same runtime class type. <p> Recall that in Java 2 an object's class (a.k.a. "runtime type") is identified in the JVM as the pair of <fully-qualified-classname;definingClassLoaderInstance> or (in shorter form) <C;L>. That is, the defining loaders identity is part of the runtime name identifying that class in the JVM. Also recall that the JVM will expect a class's defining loader to load all unloaded classes referenced by the classes it loads. <p> If interested for debugging purposes, you can find out more about which loader loaded which class by doing something like this: <blockquote><pre> System.out.println(ctx.lookup("base/PointEJBHome").getClass().getClassLoader()); System.out.println(PointEJBHome.class.getClassLoader()); </pre></blockquote> <p> You'll find when using the GUI TestRunners that the <code>PointEJBHome</code> type is defined by the JUnit TestCaseClassLoader and the object returned from <code>InitialContext.lookup()</code> was defined through the JVM's system class loader. When using the tex-based TestRunner they'll both have been loaded through the system loader. <p> If you use Ant's <batchtest> task to run your test cases and you have this problem, you can work around it by setting <code>fork="true"</code> on <code><batchtest></code>, which causes it to run each test in its own Java Virtual Machine separate from Ants launching JVM. <p> For further reading about the principles of Java dynamic classloading, the best resource is the short paper by Sheng Liang, the architect of the Java 2 classloader architecture: <a href="http://java.sun.com/people/sl/"><i>Dynamic Class Loading in the Java Virtual Machine</i></a>, OOPSLA 1998. <p></p> <hr size="1"> </li> <li><b><a name="running_11"></a>Why do I get the warning "AssertionFailedError: No tests found in XXX" when I run my test?</b> <p> Make sure the test contains one or more methods with names beginning with "test". <p> For example: <blockquote><pre> public void testSomething() { } </pre></blockquote> </p> <p> This error also commonly occurs when using the <code>addTestSuite()</code> in an attempt to create a hiearchy of test suites. For more information, see <a href="#running_14">"How do I get one test suite to invoke another?"</a>. </p> <p></p> <hr size="1"> </li> <li><b><a name="running_12"></a>Why do I see "Unknown Source" in the stack trace of a test failure, rather than the source file's line number?</b> <p> The debug option for the Java compiler must be enabled in order to see source file and line number information in a stack trace. <p> When invoking the Java compiler from the command line, use the <code>-g</code> option to generate all debugging info. <p> When invoking the Java compiler from an <a href="http://jakarta.apache.org/ant/index.html">Ant</a> task, use the <code>debug="on"</code> attribute. For example: <blockquote><pre> <javac srcdir="${src}" destdir="${build}" debug="on" /> </pre></blockquote> <p> When using older JVMs pre-Hotspot (JDK 1.1 and most/all 1.2), run JUnit with the <code>-DJAVA_COMPILER=none</code> JMV command line argument to prevent runtime JIT compilation from obscuring line number info. <p> Compiling the test source with debug enabled will show the line where the assertion failed. Compiling the non-test source with debug enabled will show the line where an exception was raised in the class under test. <p></p> <hr size="1"> </li> <li><b><a name="running_13"></a>Why does the "excluded.properties" trick not work when running JUnit's GUI from inside my favorite IDE?</b> <p> <i>(Submitted by: William Pietri)</i> <p> <p> Some IDEs come with a copy of JUnit, so your copy of JUnit in the project classpath isn't the one being used. Replace the <code>junit.jar</code> file used by the IDE with a <code>junit.jar</code> file containing a custom <code>excluded.properties</code> and your bar will once again be green. <p></p> <hr size="1"> </li> <li><b><a name="running_14"></a>How do I get one test suite to invoke another?</b> <p> <i>(Submitted by: Eric Armstrong)</i> <p> <p> To add a suite to a suite, use: <blockquote> <pre> suite.addTest(someOtherSuite.suite()); </pre> </blockquote> <p></p> <hr size="1"> </li> </ol> <!-- Best Practices --> <table border="0" cellspacing="0" cellpadding="2" width="100%" bgcolor="#33ff33"> <tr> <td align="left" width="90%"> <a name="best"><b><font size="+1">Best Practices:</font></b></a> </td> <td align="right"> <a href="#toc">top</a> </td> </tr> </table> <ol> <li><b><a name="best_1"></a>When should tests be written?</b> <p> Tests should be written before the code. Test-first programming is practiced by only writing new code when an automated test is failing. <p> Good tests tell you how to best design the system for its intended use. They effectively communicate in an executable format how to use the software. They also prevent tendencies to over-build the system based on speculation. When all the tests pass, you know you're done! <p> Whenever a c... [truncated message content] |