Writing JUnit Tests in NetBeans IDE
Writing JUnit Tests in NetBeans IDE
Writing JUnit Tests in NetBeans IDE
http://netbeans.org/kb/docs/java/junit-intro.html
Search:
Training
Java Programming Language
Support
Documentation
General Java Development External Tools and Services Java GUI Applications Java EE & Java Web Development Web Services Applications NetBeans Platform (RCP) and Module Development PHP Applications C/C++ Applications Mobile Applications Sample Applications Demos and Screencasts
More
FAQs Contribute Documentation! Docs for Earlier Releases
Note. NetBeans IDE 6.9 and 7.0 require Java Development Kit (JDK) 6.
1 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
https://svn.netbeans.org/svn/samples~samples-source-code
Click Next. 3. In the Folders to Checkout panel, click Browse to open the Browse Repository Folders dialog box. 4. Expand the root node and select samples/java/JUnitSampleSol. Click OK. 5. Specify the Local Folder for the sources. Click Finish. When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources. 6. Click Open Project in the dialog that appears when checkout is complete. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.
Note (NetBeans IDE 7.0). If you did not install the JUnit plugin when you installed the IDE, when you open the NetBeans project you will be prompted to install the JUnit plugin to resolve the reference to the JUnit libraries.
1. In the Projects window, right-click the Source Packages node of the JUnit-Sample project and choose New > Java Package from the popup menu. 2. Type sample as the package name. Click Finish. 3. Expand the Source Packages node of the JUnitSampleSol project in the Projects window.
4. Copy the classes Utils.java and Vectors.java in the JUnitSampleSol project and paste them into the sample source package in JUnit-Sample. If you look at the source code for the classes, you can see that Utils.java has three methods (computeFactorial,
concatWords, and normalizeWord) and that Vectors.java has two methods (equal and scalarMultiplication). The next
step is to create test classes for each class and write some test cases for the methods.
1. Right-click Vectors.java and choose Tools > Create JUnit Tests. 2. Select JUnit 3.x in the Select JUnit Version dialog box.
2 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
When you select JUnit 3.x the IDE removes the JUnit 4 library from the project. 3. Modify the name of the test class to VectorsJUnit3Test in the Create Tests dialog. When you change the name of the test class, you will see a warning about changing the name. The default name is based on the name of the class you are testing, with the word Test appended to the name. For example, for the class MyClass.java, the default name of the test class is MyClassTest.java. Usually it is best to keep the default name, but for this tutorial you will change the name because you will also create JUnit 4 tests in the same package and the names of the test classes must be unique. 4. Deselect Test Initializer and Test Finalizer. Click OK.
When you click OK, the IDE creates the VectorsJUnit3Test.java test class in the sample package under the Test Packages node in the Projects window.
A project requires a directory for test packages to create tests. The default location for the test packages directory is at the root level of the project, but depending on the type of project you can specify a different location for the directory in the project's Properties dialog. If you look at the generated test class VectorsJUnit3Test.java in the editor, you can see that the IDE generated the following test class with test methods for the methods equal and scalarMultiplication.
public class VectorsJUnit3Test extends TestCase { /** * Test of equal method, of class Vectors. */
3 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
public void testEqual() { System.out.println("equal"); int[] a = null; int[] b = null; boolean expResult = false; boolean result = Vectors.equal(a, b); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of scalarMultiplication method, of class Vectors. */ public void testScalarMultiplication() { System.out.println("scalarMultiplication"); int[] a = null; int[] b = null; int expResult = 0; int result = Vectors.scalarMultiplication(a, b); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
The method body of each generated test is provided solely as a guide and needs to be modified to be an actual test case. You can deselect Default Method Bodies in the Create Tests dialog if you do not want the code generated for you. When the IDE generates the names for the test methods, each method name is prepended with test because JUnit 3 uses naming conventions and reflection to identify tests. To identify test methods, each test method is required to follow the syntax test<NAME>. In JUnit 4 it is no longer necessary to use this test method naming syntax because you can use annotations to identify test methods and the test class is no longer required to extend TestCase.
1. Open VectorsJUnit3Test.java in the editor. 2. Modify the test skeleton for testScalarMultiplication by changing the value of the println and removing the generated variables. The test method should now look like the following (changes displayed in bold):
public void testScalarMultiplication() { System.out.println("* VectorsJUnit3Test: testScalarMultiplication()"); assertEquals( 0, Vectors.scalarMultiplication(new int[] { 0, 0}, new int[] { 0, 0})); assertEquals( 39, Vectors.scalarMultiplication(new int[] { 3, 4}, new int[] { 5, 6})); assertEquals(-39, Vectors.scalarMultiplication(new int[] {-3, 4}, new int[] { 5,-6})); assertEquals( } 0, Vectors.scalarMultiplication(new int[] { 5, 9}, new int[] {-9, 5})); assertEquals(100, Vectors.scalarMultiplication(new int[] { 6, 8}, new int[] { 6, 8}));
This test method uses the JUnit assertEquals method. To use the assertion, you supply the input variables and the expected result. To pass the test, the test method must successfully return all the expected results based on the supplied variables when running the tested method. You should add a sufficient number of assertions to cover the various possible permutations. 4. Modify the test skeleton for testEqual by deleting the generated method bodies and adding the following println.
5. Modify the testEqual method by adding the following assertions (displayed in bold).
4 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
public void testEqual() { System.out.println("* VectorsJUnit3Test: testEqual()"); assertTrue(Vectors.equal(new int[] {}, new int[] {})); assertTrue(Vectors.equal(new int[] {0}, new int[] {0})); assertTrue(Vectors.equal(new int[] {0, 0}, new int[] {0, 0})); assertTrue(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 0})); assertTrue(Vectors.equal(new int[] {5, 6, 7}, new int[] {5, 6, 7})); assertFalse(Vectors.equal(new int[] {}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 1})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 1, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {1, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 1}, new int[] {0, 0, 3})); }
This test uses the JUnit assertTrue and assertFalse methods to test a variety of possible results. For the test of this method to pass, the assertTrue must all be true and assertFalse must all be false. 6. Save your changes. Compare: Writing Test Methods for Vectors.java (JUnit 4)
1. Right-click Utils.java and choose Tools > Create JUnit Tests. 2. Select Test Initializer and Test Finalizer in the dialog box, if unselected. 3. Modify the name of the test class to UtilsJUnit3Test in the Create Tests dialog box. Click OK. When you click OK, the IDE creates the test file UtilsJUnit3Test.java in the Test Packages > samples directory. You can see that in addition to creating the test skeletons testComputeFactorial, testConcatWords, and testNormalizeWord for the methods in Utils.java, the IDE also creates the test initializer method setUp and the test finalizer method tearDown.
1. Make the following changes (displayed in bold) to add a println to each method.
@Override protected void setUp() throws Exception { super.setUp(); System.out.println("* UtilsJUnit3Test: setUp() method"); } @Override protected void tearDown() throws Exception { super.tearDown(); System.out.println("* UtilsJUnit3Test: tearDown() method"); }
When you run the test the println text for each methods will appear in the JUnit Test Results output window. If you do not add the println, there is no output to show that the methods were run.
5 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
add a new test method called testHelloWorld that uses a single simple assertion to test if the method concatenates the strings correctly. The assertEquals in the test case uses the syntax assertEquals(EXPECTED_RESULT, ACTUAL_RESULT) to test if the expected result is equal to the actual result. In this case, if the input to the method concatWords is "Hello", ", ", "world" and "!", the expected result should equal "Hello, world!".
1. Delete the generated test method testConcatWords in UtilsJUnit3Test.java. 2. Add the following method to test the concatWords method.
public void testHelloWorld() { assertEquals("Hello, world!", Utils.concatWords("Hello", ", ", "world", "!")); }
3. Add a println statement to display text about the test in the JUnit Test Results window.
public void testHelloWorld() { System.out.println("* UtilsJUnit3Test: test method 1 - testHelloWorld()"); assertEquals("Hello, world!", Utils.concatWords("Hello", ", ", "world", "!"));
TimeoutException unless the computeFactorial thread completes first. You will add a message so that a message is
displayed if a TimeoutException is thrown.
1. Delete the generated test method testComputeFactorial. 2. Add the testWithTimeout method that calculates the factorial of a randomly generated number.
public void testWithTimeout() throws InterruptedException, TimeoutException { final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println("computing " + factorialOf + '!'); Thread testThread = new Thread() { public void run() { System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); } }; }
3. Fix your imports to import java.util.concurrent.TimeoutException. 4. Add the following code (displayed in bold) to the method to interrupt the thread and display a message if the test takes too long to execute.
Thread testThread = new Thread() { public void run() { System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); } }; testThread.start(); Thread.sleep(1000); testThread.interrupt(); if (testThread.isInterrupted()) { throw new TimeoutException("the test took too long to complete"); } }
You can modify the Thread.sleep line to change the number of milliseconds before the timeout is thrown. 5. Add the following println (displayed in bold) to print the text about the test in the JUnit Test Results window.
public void testWithTimeout() throws InterruptedException, TimeoutException { System.out.println("* UtilsJUnit3Test: test method 2 - testWithTimeout()"); final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println("computing " + factorialOf + '!');
6 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
1. Add the following testExpectedException method that invokes the computeFactorial method with an input of -5.
public void testExpectedException() { try { final int factorialOf = -5; System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); fail("IllegalArgumentException was expected"); } catch (IllegalArgumentException ex) { } }
2. Add the following println (displayed in bold) to print the text about the test in the JUnit Test Results window.
Disabling a Test
This test demonstrates how to temporarily disable a test method. In JUnit 3, if a method name does not start with test it is not recognized as a test method. In this case you prepend DISABLED_ to the name of the test method to disable it.
1. Delete the generated test method testNormalizeWord. 2. Add the following test method to the test class.
public void testTemporarilyDisabled() throws Exception { System.out.println("* UtilsJUnit3Test: test method 4 - checkExpectedException()"); assertEquals("Malm\u00f6", Utils.normalizeWord("Malmo\u0308")); }
The test method testTemporarilyDisabled will run if you run the test class. 3. Prepend DISABLED_ (displayed in bold) to the name of the test method.
public void DISABLED_testTemporarilyDisabled() throws Exception { System.out.println("* UtilsJUnit3Test: test method 4 - checkExpectedException()"); assertEquals("Malm\u00f6", Utils.normalizeWord("Malmo\u0308")); }
Compare: Disabling a Test (JUnit 4) Now that you have written the tests, you can run the test and see the test output in the JUnit Test Results window.
1. Right-click the JUnit-Sample project node in the Projects window and choose Set as Main Project. 2. Choose Run > Test Project (JUnit-Sample) from the main menu. When you run the test you will see one of the following results in the JUnit Test Results window.
In this image (click the image to see a larger image) you can see that the project passed all the tests. The left pane displays the results of the individual test methods and the right pane displays the test output. If you look at the output you can see the order that the tests were run. The println that you added to each of the test methods printed out the name of the test to the output window. You can also see that in UtilJUnit3Test the setUp method was run before each test method and the tearDown method was run after each method.
7 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
In this image (click the image to see a larger image) you can see that the project failed one of the tests. The testTimeout method took too long to complete and the test thread was interrupted, causing that test to fail. It took longer than 1000 milliseconds to compute the factorial of the randomly generated number (22991). The next step after you create your unit test classes is to create test suites. See Creating JUnit 3 Test Suites to see how to run specified tests as a group so you do not have to run each test individually.
1. Right-click Vectors.java and choose Tools > Create JUnit Tests. 2. Select JUnit 4.x in the Select JUnit Version dialog box.
When you select JUnit 4.x the IDE removes the JUnit 3 libraries. If your project has JUnit 4 libraries you can write and run JUnit 3 and JUnit 4 tests. 3. Modify the name of the test class to VectorsJUnit4Test in the Create Tests dialog. When you change the name of the test class, you will see a warning about changing the name. The default name is based on the name of the class you are testing, with the word Test appended to the name. For example, for the class MyClass.java, the default name of the test class is MyClassTest.java. Unlike JUnit 3, in JUnit 4, test are not required to end with the word Test. Usually it is best to keep the default name, but because you are creating all the JUnit tests in the same package in this tutorial the names of the test classes have to be unique. 4. Deselect Test Initializer and Test Finalizer. Click OK.
8 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
When you click OK, the IDE creates the VectorsJUnit4Test.java test class in the sample package under the Test Packages node in the Projects window.
A project requires a directory for test packages to create tests. The default location for the test packages directory is at the root level of the project, but you can specify a different location for the directory in the project's Properties dialog. If you look at VectorsJUnit3Test.java in the editor, you can see that the IDE generated the test methods testEqual and
testScalarMultiplication. In VectorsJUnit4Test.java, each test method is annotated with @Test. The IDE generated the
names for the test methods based on the names of the method in Vectors.java but the name of the test method is not required to have test prepended. The default body of each generated test method is provided solely as a guide and needs to be modified to be actual test cases. You can deselect Default Method Bodies in the Create Tests dialog if you do not want the bodies of the method generated for you. The IDE also generated the following test class initializer and finalizer methods:
@BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { }
The IDE generates the class initializer and finalizer methods by default when creating JUnit 4 test classes. The annotations
@BeforeClass and @AfterClass are used to mark methods that should be run before and after running the test class. You can
delete the methods because you will not need them to test Vectors.java. You can configure the methods that are generated by default by configuring the JUnit options in the Options window.
9 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
the names of the test methods. In JUnit 4 you have greater flexibility when naming test methods because test methods are indicated by the @Test annotation and do not require the word test prepended to test method names.
1. Open VectorsJUnit4Test.java in the editor. 2. Modify the test method for testScalarMultiplication by changing the name of the method, the value of the println and removing the generated variables. The test method should now look like the following (changes displayed in bold):
When writing tests it is not necessary to change the printed output. You do this in this exercise so that it is easier to identify the test results in the output window. 3. Now add some assertions to test the method.
@Test public void ScalarMultiplicationCheck() { System.out.println("* VectorsJUnit4Test: ScalarMultiplicationCheck()"); assertEquals( 0, Vectors.scalarMultiplication(new int[] { 0, 0}, new int[] { 0, 0})); assertEquals( 39, Vectors.scalarMultiplication(new int[] { 3, 4}, new int[] { 5, 6})); assertEquals(-39, Vectors.scalarMultiplication(new int[] {-3, 4}, new int[] { 5,-6})); assertEquals( } 0, Vectors.scalarMultiplication(new int[] { 5, 9}, new int[] {-9, 5})); assertEquals(100, Vectors.scalarMultiplication(new int[] { 6, 8}, new int[] { 6, 8}));
In this test method you use the JUnit assertEquals method. To use the assertion, you supply the input variables and the expected result. To pass the test, the test method must successfully return all the expected results based on the supplied variables when running the tested method. You should add a sufficient number of assertions to cover the various possible permutations. 4. Change the name of the testEqual test method to equalsCheck. 5. Delete the the generated method body of the equalsCheck test method. 6. Add the following println to the equalsCheck test method.
7. Modify the equalsCheck method by adding the following assertions (displayed in bold).
@Test public void equalsCheck() { System.out.println("* VectorsJUnit4Test: equalsCheck()"); assertTrue(Vectors.equal(new int[] {}, new int[] {})); assertTrue(Vectors.equal(new int[] {0}, new int[] {0})); assertTrue(Vectors.equal(new int[] {0, 0}, new int[] {0, 0})); assertTrue(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 0})); assertTrue(Vectors.equal(new int[] {5, 6, 7}, new int[] {5, 6, 7})); assertFalse(Vectors.equal(new int[] {}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 1})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 1, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {1, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 1}, new int[] {0, 0, 3})); }
This test uses the JUnit assertTrue and assertFalse methods to test a variety of possible results. For the test of this method to pass, the assertTrue must all be true and assertFalse must all be false.
10 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
Utils.java. The IDE also generated initializer and finalizer methods for the test and the test class.
@BeforeClass public static void setUpClass() throws Exception { System.out.println("* UtilsJUnit4Test: @BeforeClass method"); } @AfterClass public static void tearDownClass() throws Exception { System.out.println("* UtilsJUnit4Test: @AfterClass method"); } @Before public void setUp() { System.out.println("* UtilsJUnit4Test: @Before method"); } @After public void tearDown() { System.out.println("* UtilsJUnit4Test: @After method"); }
Compare: Test initializers and finalizers (JUnit 3) When you run the test class the println text you added is displayed in the output pane of the JUnit Test Results window. If you do not add the println, there is no output to indicate that the initializer and finalizer methods were run.
11 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
This simple test case tests the concatWords method. Instead of using the generated test method testConcatWords, you will add a new test method called helloWorldCheck that uses a single simple assertion to test if the method concatenates the strings correctly. The assertEquals in the test case uses the syntax assertEquals(EXPECTED_RESULT, ACTUAL_RESULT) to test if the expected result is equal to the actual result. In this case, if the input to the method concatWords is "Hello", ",", "world" and "!", the expected result should equal "Hello, world!".
1. Delete the generated test method testConcatWords. 2. Add the following helloWorldCheck method to test Utils.concatWords.
@Test public void helloWorldCheck() { assertEquals("Hello, world!", Utils.concatWords("Hello", ", ", "world", "!")); }
3. Add a println statement to display text about the test in the JUnit Test Results window.
@Test public void helloWorldCheck() { System.out.println("* UtilsJUnit4Test: test method 1 - helloWorldCheck()"); assertEquals("Hello, world!", Utils.concatWords("Hello", ", ", "world", "!"));
1. Delete the generated test method testComputeFactorial. 2. Add the testWithTimeout method that calculates the factorial of a randomly generated number.
@Test public void testWithTimeout() { final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println("computing " + factorialOf + '!'); System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); }
3. Add the following code (displayed in bold) to set the timeout and to interrupt the thread if the method takes too long to execute.
@Test(timeout=1000) public void testWithTimeout() { final int factorialOf = 1 + (int) (30000 * Math.random());
You can see that the timeout is set to 1000 milliseconds. 4. Add the following println (displayed in bold) to print the text about the test in the JUnit Test Results window.
@Test(timeout=1000) public void testWithTimeout() { System.out.println("* UtilsJUnit4Test: test method 2 - testWithTimeout()"); final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println("computing " + factorialOf + '!');
1. Add the following testExpectedException method that invokes the computeFactorial method with an input of -5.
@Test public void checkExpectedException() { final int factorialOf = -5; System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); }
12 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
2. Add the following property (displayed in bold) to the @Test annotation to specify that the test is expected to throw
IllegalArgumentException. @Test(expected=IllegalArgumentException.class) public void checkExpectedException() { final int factorialOf = -5; System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); }
3. Add the following println (displayed in bold) to print the text about the test in the JUnit Test Results window.
@Test (expected=IllegalArgumentException.class) public void checkExpectedException() { System.out.println("* UtilsJUnit4Test: test method 3 - checkExpectedException()"); final int factorialOf = -5; System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); }
Disabling a Test
This test demonstrates how to temporarily disable a test method. In JUnit 4 you simply add the @Ignore annotation to disable the test.
1. Delete the generated test method testNormalizeWord. 2. Add the following test method to the test class.
@Test public void temporarilyDisabledTest() throws Exception { System.out.println("* UtilsJUnit4Test: test method 4 - checkExpectedException()"); assertEquals("Malm\u00f6", Utils.normalizeWord("Malmo\u0308")); }
The test method temporarilyDisabledTest will run if you run the test class. 3. Add the @Ignore annotation (displayed in bold) above @Test to disable the test.
@Ignore @Test public void temporarilyDisabledTest() throws Exception { System.out.println("* UtilsJUnit4Test: test method 4 - checkExpectedException()"); assertEquals("Malm\u00f6", Utils.normalizeWord("Malmo\u0308")); }
4. Fix your imports to import org.junit.Ignore. Compare: Disabling a Test (JUnit 3) Now that you have written the tests you can run the test and see the test output in the JUnit Test Results window.
1. Right-click UtilsJUnit4Test.java in the Projects window. 2. Choose Test File. When you run UtilsJUnit4Test.java the IDE only runs the tests in the test class. If the class passes all the tests you will see something similar to the following image in the JUnit Test Results window.
In this image (click the image to see a larger image) you can see that the IDE ran the JUnit test on Utils.java and that the class passed all the tests. The left pane displays the results of the individual test methods and the right pane displays the test output. If you look at the output you can see the order that the tests were run. The println that you added to each of the test methods printed out the name of the test to Test Results window and the Output window. You can see that in UtilsJUnit4Test the test class initializer method annotated with @BeforeClass was run before any of the other methods and it was run only once. The test class finalizer method annotated with @AfterClass was run last, after all the other
13 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
methods in the class. The test initializer method annotated with @Before was run before each test method. The controls in the left side of the Test Results window enable you to easily run the test again. You can use the filter to toggle between displaying all test results or only the failed tests. The arrows enable you to skip to the next failure or the previous failure. When you right-click a test result in the Test Results window, the popup menu enables you to choose to go to the test's source, run the test again or debug the test. The next step after creating your unit test classes is to create test suites. See Creating JUnit 4 Test Suites to see how to run specified tests as a group so you do not have to run each test individually.
When you click Finish, the IDE creates the test suite class in the sample package and opens the class in the editor. The test suite will contain the following code.
public class JUnit3TestSuite extends TestCase { public JUnit3TestSuite(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite("JUnit3TestSuite"); return suite; } }
14 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
6. Modify the suite() method to add the test classes that will be run as part of the suite.
public JUnit3TestSuite(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite("JUnit3TestSuite"); suite.addTest(new TestSuite(sample.VectorsJUnit3Test.class)); suite.addTest(new TestSuite(sample.UtilsJUnit3Test.class)); return suite; }
When you run the test suite the IDE will run the test classes in the order that they are listed.
1. Expand the Test Packages node in the Projects window. 2. Right-click the test suite class and choose Test File. When you run the test suite the IDE runs the tests included in the suite in the order they are listed. The results are displayed in the JUnit Test Results window.
In this image (click the image to see a larger image) you can see the test results for a JUnit 3 test suite. The test suite ran the
UtilsJUnit3Test and VectorsJUnit3Test test classes as a single test and displayed the test results in the left pane as the
results of a single test. The output in the right pane is the same as when you run the test individually.
In this image (click the image to see a larger image) you can see the test results for a JUnit 4 test suite. The test suite ran the
UtilsJUnit4Test and VectorsJUnit4Test test classes as a single test and displayed the test results in the left pane as the
results of a single test. The output in the right pane is the same as when you run the test individually.
In this image (click the image to see a larger image) you can see the test results for a mixed test suite. This test suite includes the
15 of 16
05/01/2012 12:00
http://netbeans.org/kb/docs/java/junit-intro.html
JUnit 4 test suite and one of the JUnit 3 test classes. The test suite ran the UtilsJUnit3Test.java and JUnit4TestSuite.java test classes as a single test and displayed the test results in the left pane as the results of a single test. The output in the right pane is the same as running the test individually.
Summary
This tutorial was a basic introduction to creating JUnit unit tests and test suites in NetBeans IDE. The IDE supports JUnit 3 and JUnit 4, and this document demonstrated some of the changes introduced in JUnit 4 that are designed to make creating and running tests simpler. As demonstrated in this tutorial, one of the main improvements in JUnit 4 is support for annotations. In JUnit 4 you can now use annotations to do the following: Identify a test using the @Test annotation instead of naming convention Identify setUp and tearDown methods with @Before and @After annotations Identify setUp and tearDown methods that apply to the entire test class. Methods annotated with @BeforeClass are run only once, before any test methods in the class are run. Methods annotated with @AfterClass are also run only once, after all the test methods have finished. Identify expected exceptions Identify tests that should be skipped using the @Ignore annotation Specify a timeout parameter for a test For more information about using JUnit and other changes introduced in JUnit 4, see the following resources: JUnit group at Yahoo groups www.junit.org Testing code often helps ensure that small changes made in the code do not break the application. Automated testing tools like JUnit streamline the process of testing and frequent testing can help catch coding errors early.
See Also
For more information about using NetBeans IDE to develop Java applications, see the following resources: Creating, Importing, and Configuring Java Projects Basic IDE and Java Programming Learning Trail
SiteMap
About Us
Contact
Legal
By use of this website, you agree to the NetBeans Policies and Terms of Use. 2011, Oracle Corporation and/or its affiliates.
Companion Projects:
Sponsored by
16 of 16
05/01/2012 12:00