Writing JUnit Tests in NetBeans IDE

  • Creating the Project
    • Creating the Java Class Library Projection
  • Creating the Java Classes
  • Writing JUnit 3 Unit Tests
    • Creating a Test Class for Vectors.coffee
    • Writing Test Methods for Vectors.java
    • Creating a Examination Class for Utils.coffee
    • Writing Test Methods for Utils.java
    • Running the Tests
  • Writing JUnit 4 Tests
    • Creating a Test Class for Vectors.coffee
    • Writing Test Methods for Vectors.java
    • Creating a Test Class for Utils.java
    • Writing Test Methods for Utils.java
    • Running the Tests
  • Creating Test Suites
    • Creating JUnit iii Test Suites
    • Creating JUnit 4 Test Suites
    • Running Test Suites
  • Determination

This tutorial introduces the basics of writing and running JUnit unit tests in NetBeans IDE. Testing an application is an integral role of the development cycle, and writing and maintaining unit tests can help ensure that the individual methods in your source lawmaking work correctly. The IDE'south integrated support for the JUnit unit of measurement testing framework enables you to apace and easily create JUnit tests and exam suites.

In this tutorial you create simple JUnit 3 and JUnit 4 unit tests and test suites for a Java class library project. The first part of the tutorial shows how to create tests in JUnit 3. The second part shows how to create the aforementioned tests in JUnit 4 using JUnit annotations. Information technology is not necessary to consummate both parts of the tutorial because the tests are the same, but seeing how the tests are written in both versions enables y'all to come across some of the changes introduced in JUnit 4.

Creating the Project

To complete this tutorial y'all first create a Coffee class library project called JUnit-Sample. Subsequently you create the projection, you lot copy two classes from the sample project JUnitSampleSol to your project JUnit-Sample.

Creating the Java Class Library Project

  1. Choose File > New Project from the main menu.

  2. Select Java Form Library from the Coffee category and click Next.

  3. Type JUnit-Sample for the project and set the project location.

  4. Deselect the Utilize Defended Folder choice, if selected.

For this tutorial there is little reason to copy project libraries to a dedicated folder considering you lot will not demand to share libraries with other users or projects.

Click Stop.

The first time that you create a JUnit exam the IDE prompts you to select a version and so adds a Examination Libraries node and the JUnit library.

Creating the Java Classes

In this exercise yous copy the files Utils.java and Vectors.coffee from the sample project JUnitSampleSol into the form library project that y'all created.

  1. In the Projects window, correct-click the Source Packages node of the JUnit-Sample project and choose New > Java Packet from the popup menu.

  2. Type sample as the bundle name. Click Finish.

  3. Open up the JUnitSampleSol projection (if not already open up) and aggrandize the Source Packages node in the Projects window.

projects window

  1. Copy the classes Utils.java and Vectors.coffee in the JUnitSampleSol project and paste them into the sample source parcel in JUnit-Sample.

If you look at the source lawmaking for the classes, you lot can see that Utils.java has iii methods ( computeFactorial , concatWords , and normalizeWord ) and that Vectors.java has ii methods ( equal and scalarMultiplication ). The next footstep is to create test classes for each form and write some test cases for the methods.

You tin shut the JUnitSampleSol project because you will not demand it again. The JUnitSampleSol project contains all the tests described in this document.

Writing JUnit 3 Unit of measurement Tests

In this part of the tutorial you create basic JUnit iii unit tests for the classes Vectors.java and Utils.java . You will utilise the IDE to create skeleton test classes that are based on the classes in your project. You will then modify the generated test methods and add new test methods.

The IDE prompts you to cull a JUnit version the first fourth dimension that you use the IDE to create tests for y'all in the projection. The version that you select becomes the default JUnit version and the IDE will generate all subsequent tests and examination suites for that version.

Creating a Test Class for Vectors.java

In this do you create a JUnit exam skeleton for Vectors.coffee . Yous volition also select JUnit as the examination framework and JUnit 3 every bit the version.

If you are using NetBeans IDE 7.1 or earlier you do non need to specify the test framework considering JUnit is specified by default. From NetBeans IDE 7.2 onwards, y'all have the option of specifying JUnit or TestNG as the test framework.
  1. Right-click Vectors.coffee and choose Tools > Create Tests.

  2. Modify the proper name of the test grade to VectorsJUnit3Test in the Create Tests dialog.

When yous change the name of the test class, yous volition see a alarm about changing the name. The default name is based on the name of the class you lot are testing, with the give-and-take Test appended to the name. For example, for the form MyClass.coffee , the default name of the test form is MyClassTest.java . Usually information technology is best to keep the default name, but for this tutorial y'all will change the proper name considering y'all will also create JUnit 4 tests in the aforementioned parcel and the names of the exam classes must be unique.

  1. Select JUnit in the Framework dropdown listing.

  2. Deselect Test Initializer and Test Finalizer. Click OK.

junit3 vectors createtests

  1. Select JUnit three.x in the Select JUnit Version dialog box.

junit3 select version

When y'all select JUnit iii.x the IDE adds the JUnit 3 library to the projection.

When you click Select, the IDE creates the VectorsJUnit3Test.java test course in the sample packet under the Test Packages node in the Projects window.

projects window2

A project requires a directory for examination packages to create tests. The default location for the test packages directory is at the root level of the project, only depending on the blazon of projection yous tin specify a different location for the directory in the projection'south Properties dialog.

If you await at the generated test class VectorsJUnit3Test.coffee in the editor, you tin see that the IDE generated the following test class with examination methods for the methods equal and scalarMultiplication .

                  public class VectorsJUnit3Test extends TestCase {     /**      * Test of equal method, of class Vectors.      */     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 exam code and remove the default call to neglect.         fail("The test case is a epitome.");     }      /**      * Exam of scalarMultiplication method, of class Vectors.      */     public void testScalarMultiplication() {         Organization.out.println("scalarMultiplication");         int[] a = goose egg;         int[] b = naught;         int expResult = 0;         int effect = Vectors.scalarMultiplication(a, b);         assertEquals(expResult, consequence);         // TODO review the generated examination lawmaking and remove the default call to fail.         fail("The examination case is a prototype.");     } }                

The method torso of each generated test is provided solely as a guide and needs to be modified to be an actual test case. You tin 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 considering JUnit 3 uses naming conventions and reflection to identify tests. To identify examination methods, each exam method is required to follow the syntax test_<NAME>_ .

In JUnit 4, information technology is no longer necessary to use this test method naming syntax because you can use annotations to place test methods and the exam course is no longer required to extend TestCase .

Writing Test Methods for Vectors.coffee

In this exercise you modify the generated examination methods to make them functioning tests and alter the default output messages. Yous do not need to alter the output messages to run the tests, but yous may want to alter the output to help identify the results displayed in the JUnit Test Results output window.

  1. Open VectorsJUnit3Test.java in the editor.

  2. Change the test skeleton for testScalarMultiplication by changing the value of the println and removing the generated variables. The exam method should now look like the following (changes displayed in bold):

                  public void testScalarMultiplication() {     System.out.println("** VectorsJUnit3Test: testScalarMultiplication()*");     assertEquals(expResult, consequence); }                
  1. Now add together some assertions to examination the method.

                  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, iv}, new int[] { 5, 6}));     assertEquals(-39, Vectors.scalarMultiplication(new int[] {-3, 4}, new int[] { 5,-6}));     assertEquals(  0, Vectors.scalarMultiplication(new int[] { 5, ix}, new int[] {-9, five}));     assertEquals(100, Vectors.scalarMultiplication(new int[] { 6, eight}, new int[] { 6, viii}));* }                

This test method uses the JUnit assertEquals method. To apply the assertion, you supply the input variables and the expected event. To laissez passer the exam, the test method must successfully render all the expected results based on the supplied variables when running the tested method. You should add a sufficient number of assertions to embrace the various possible permutations.

  1. Change the test skeleton for testEqual by deleting the generated method bodies and adding the following println .

                                      *Organisation.out.println("* VectorsJUnit3Test: testEqual()");*                

The examination method should now look like the following:

                  public void testEqual() {     System.out.println("* VectorsJUnit3Test: testEqual()"); }                
  1. Alter the testEqual method by adding the following assertions (displayed in bold).

                  public void testEqual() {     Arrangement.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[] {five, vi, vii}, new int[] {5, 6, seven}));      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, ane}));     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, ane}, new int[] {0, 0, iii}));* }                

This test uses the JUnit assertTrue and assertFalse methods to test a diverseness of possible results. For the test of this method to pass, the assertTrue must all be truthful and assertFalse must all be false.

  1. Save your changes.

Creating a Test Course for Utils.java

Yous now create the test skeletons for Utils.java . When yous created the test in the previous exercise, the IDE prompted you for the version of JUnit. You are not prompted to select a version this time.

  1. Right-click Utils.java and choose Tools > Create Tests.

  2. Select JUnit in the Framework dropdown list if not selected.

  3. Select Test Initializer and Examination Finalizer in the dialog box, if non selected.

  4. Modify the proper name of the examination 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 too creates the test initializer method setUp and the test finalizer method tearDown .

Writing Test Methods for Utils.java

In this do you lot add together some examination cases that illustrate some common JUnit test elements. Y'all also add a println to the methods because some methods practice not impress any output by default. Past calculation a println to the methods you can later look in the JUnit test outcome window to see if the methods were run and the lodge in which they were run.

Test Initializers and Finalizers

The setUp and tearDown methods are used to initialize and finalize test conditions. You practise not need the setUp and tearDown methods to test Utils.coffee , only they are included hither to demonstrate how they work.

The setUp method is a exam initialization method and is run before each examination case in the examination class. A test initialization method is not required for running tests, simply if you need to initialize some variables before you run a test, you utilize the examination initializer method.

The tearDown method is a test finalizer method and is run later each test case in the exam form. A exam finalizer method is non required for running tests, just you may need a finalizer to clean up whatever data that was required when running the test cases.

Make the following changes (displayed in bold) to add together 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();     *Organisation.out.println("* UtilsJUnit3Test: tearDown() method");* }                  

When you run the examination the println text for each methods will appear in the JUnit Exam Results output window. If you do not add together the println , there is no output to show that the methods were run.

Testing Using a Simple Exclamation

This uncomplicated examination case tests the concatWords method. Instead of using the generated test method testConcatWords , you lot volition add together a new test method called testHelloWorld that uses a single simple assertion to exam 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 outcome is equal to the actual result. In this case, if the input to the method concatWords is " Howdy ", " , ", " world " and " ! ", the expected event should equal "Hello, world!" .

  1. Delete the generated examination method testConcatWords in UtilsJUnit3Test.java .

  2. Add the following method to test the concatWords method.public void testHelloWorld() { assertEquals("Hello, world!", Utils.concatWords("Howdy", ", ", "world", "!")); }

    1. Add a println statement to display text about the examination in the JUnit Test Results window.

                    public void testHelloWorld() {     *System.out.println("* UtilsJUnit3Test: examination method 1 - testHelloWorld()");*     assertEquals("Hello, world!", Utils.concatWords("Hullo", ", ", "world", "!"));                  

Compare: Testing Using a Simple Exclamation (JUnit 4)

Testing Using a Timeout

This test demonstrates how to check if a method is taking too long to consummate. If the method is taking too long, the exam thread is interrupted and the examination fails. You can specify the time limit in the test.

The test method invokes the computeFactorial method in Utils.coffee . You can assume that the computeFactorial method is correct, merely in this example you lot want to examination if the ciphering is completed within 1000 milliseconds. The computeFactorial thread and a test thread are started at the same time. The test thread will stop after 1000 milliseconds and throw a TimeoutException unless the computeFactorial thread completes first. You will add a bulletin so that a message is displayed if a TimeoutException is thrown.

  1. Delete the generated exam 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() {             Arrangement.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf));         }     }; }*
    1. Gear up your imports to import java.util.concurrent.TimeoutException .

    2. Add the following lawmaking (displayed in assuming) to the method to interrupt the thread and display a message if the examination takes besides 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 besides long to complete");     }* }                  

You tin can modify the Thread.sleep line to modify the number of milliseconds earlier the timeout is thrown.

  1. Add the post-obit println (displayed in bold) to impress the text most the test in the JUnit Test Results window.

                    public void testWithTimeout() throws InterruptedException, TimeoutException {     *System.out.println("* UtilsJUnit3Test: exam method two - testWithTimeout()");*     last int factorialOf = 1 + (int) (30000 * Math.random());     Organization.out.println("calculating " + factorialOf + '!');                  

Compare: Testing Using a Timeout (JUnit iv)

Testing for an Expected Exception

This test demonstrates how to exam for an expected exception. The method fails if it does not throw the specified expected exception. In this case you lot are testing that the computeFactorial method throws an IllegalArgumentException if the input variable is a negative number (-5).

  1. Add the following testExpectedException method that invokes the computeFactorial method with an input of -five.public void testExpectedException() { try { final int factorialOf = -5; Organisation.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); fail("IllegalArgumentException was expected"); } catch (IllegalArgumentException ex) { } }

    1. Add the following println (displayed in bold) to print the text virtually the test in the JUnit Test Results window.

                    public void testExpectedException() {     *Arrangement.out.println("* UtilsJUnit3Test: test method 3 - testExpectedException()");*     try {                  

Compare: Testing for an Expected Exception (JUnit iv)

Disabling a Examination

This test demonstrates how to temporarily disable a test method. In JUnit 3, if a method proper name does not start with examination it is non recognized equally a test method. In this case you prepend DISABLED_ to the name of the test method to disable information technology.

  1. Delete the generated test method testNormalizeWord .

  2. Add the following test method to the test grade.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 yous run the examination class.

  1. Prepend DISABLED_ (displayed in bold) to the proper name of the exam 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)

At present that yous have written the tests, you tin can run the test and see the test output in the JUnit Test Results window.

Running the Tests

When you run a JUnit test the results are displayed in the Test Results window of the IDE. Yous can run private JUnit examination classes or yous tin choose Run > Test PROJECT_NAME from the main card to run all the tests for the projection. If you choose Run > Test, the IDE runs all the test classes in the Test Packages binder. To run an private test class, correct-click the test class under the Test Packages node and choose Run File.

  1. Choose Run > Set Principal Project in the main menu and select the JUnit-Sample project.

  2. Choose Run > Test Projection (JUnit-Sample) from the main menu.

  3. Choose Window > IDE Tools > Test Results to open the Test Results window.

When you run the test you will encounter one of the post-obit results in the JUnit Test Results window.

junit3 test pass sm

In this image (click the prototype to see a larger image) yous can see that the project passed all the tests. The left pane displays the results of the individual examination methods and the right pane displays the test output. If you look at the output you tin 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. Yous can also encounter that in UtilJUnit3Test the setUp method was run earlier each exam method and the tearDown method was run after each method.

junit3 test fail sm

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 as well 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 adjacent step later you lot create your unit exam classes is to create test suites. Run across Creating JUnit 3 Exam Suites to see how to run specified tests every bit a group and so you do not have to run each test individually.

Writing JUnit 4 Tests

In this practise yous create JUnit four unit tests for the classes Vectors.coffee and Utils.java . The JUnit 4 test cases are the same as the JUnit three examination cases, merely you lot will see that the syntax for writing the tests is simpler.

You volition utilise the IDE's wizards to create test skeletons based on the classes in your project. The starting time time that you use the IDE to create some test skeletons for y'all, the IDE prompts you to choose the JUnit version.

Annotation. If you already selected JUnit iii.x as the default version for your tests, you lot need to change the default version to JUnit 4.x. To modify the default JUnit version, aggrandize the Test Libraries node, correct-click the JUnit library and choose Remove. You can at present use the Add Library dialog box to explicitly add the JUnit 4 library or you tin can select version 4.10 when you lot are prompted to select the JUnit version when you create a new test. You can still run JUnit iii tests, but whatever new tests y'all create volition apply JUnit 4.

Creating a Examination Course for Vectors.java

In this practice you will create the JUnit test skeletons for Vectors.java .

If you are using NetBeans IDE 7.one or before you exercise non need to specify the examination framework because JUnit is specified by default. From NetBeans IDE seven.2 onwards, yous have the option of specifying JUnit or TestNG as the exam framework.
  1. Right-click Vectors.java and choose Tools > Create Tests.

  2. Change the name of the examination class to VectorsJUnit4Test in the Create Tests dialog.

When you lot change the name of the examination class, yous volition encounter a alert virtually changing the proper noun. The default name is based on the proper noun of the class you are testing, with the discussion Test appended to the name. For example, for the class MyClass.java , the default name of the examination class is MyClassTest.java . Unlike JUnit 3, in JUnit 4, examination are not required to finish with the word Exam. Usually it is best to keep the default name, but because y'all are creating all the JUnit tests in the same package in this tutorial the names of the test classes have to exist unique.

  1. Select JUnit in the Framework dropdown list.

  2. Deselect Test Initializer and Test Finalizer. Click OK.

junit4 vectors createtests

  1. Select JUnit 4.ten in the Select JUnit Version dialog box. Click Select.

junit4 select version

When you lot click OK, the IDE creates the VectorsJUnit4Test.java test course in the sample package under the Test Packages node in the Projects window.

projects window3

A project requires a directory for test packages to create tests. The default location for the exam packages directory is at the root level of the projection, but you tin can specify a different location for the directory in the project's Backdrop dialog.

If y'all wait at VectorsJUnit3Test.java in the editor, you tin see that the IDE generated the exam methods testEqual and testScalarMultiplication . In VectorsJUnit4Test.java , each examination method is annotated with @Exam . 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 exam cases.

You tin deselect Default Method Bodies in the Create Tests dialog if you do not want the bodies of the method generated for y'all.

The IDE also generated the following test grade 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 subsequently running the test class. You tin delete the methods because yous will non demand them to test Vectors.java .

Yous tin can configure the methods that are generated past default by configuring the JUnit options in the Options window.

For JUnit four tests, notice that by default the IDE adds a static import declaration for org.junit.Assert.* .

Writing Test Methods for Vectors.java

In this exercise yous modify each of the generated test methods to examination the methods using the JUnit assert method and to change the names of the test methods. In JUnit 4 you lot have greater flexibility when naming test methods because examination methods are indicated past the @Test annotation and do non require the word test prepended to examination 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 at present look similar the post-obit (changes displayed in assuming):

                  @Examination public void *ScalarMultiplicationCheck*() {     System.out.println("** VectorsJUnit4Test: ScalarMultiplicationCheck()*");     assertEquals(expResult, result); }                
When writing tests it is not necessary to change the printed output. You exercise this in this do so that information technology is easier to identify the examination results in the output window.
  1. Now add together 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, six}));     assertEquals(-39, Vectors.scalarMultiplication(new int[] {-three, four}, new int[] { 5,-6}));     assertEquals(  0, Vectors.scalarMultiplication(new int[] { v, 9}, new int[] {-9, 5}));     assertEquals(100, Vectors.scalarMultiplication(new int[] { 6, 8}, new int[] { 6, eight}));* }                

In this test method you apply the JUnit assertEquals method. To use the assertion, you supply the input variables and the expected upshot. 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 encompass the various possible permutations.

  1. Modify the proper name of the testEqual test method to equalsCheck .

  2. Delete the the generated method body of the equalsCheck test method.

  3. Add the following println to the equalsCheck test method.System.out.println(" VectorsJUnit4Test: equalsCheck()");*

The test method should now expect like the post-obit:

                  @Test public void equalsCheck() {     Organization.out.println("* VectorsJUnit4Test: equalsCheck()"); }                
  1. Modify the equalsCheck method by adding the following assertions (displayed in assuming).

                  @Exam 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, vii}));      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, ane, 0}));     assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {i, 0, 0}));     assertFalse(Vectors.equal(new int[] {0, 0, 1}, new int[] {0, 0, iii}));* }                

This examination uses the JUnit assertTrue and assertFalse methods to test a multifariousness of possible results. For the test of this method to pass, the assertTrue must all be truthful and assertFalse must all be false.

Creating a Exam Class for Utils.java

You will at present create the JUnit exam methods for Utils.java . When you created the test course in the previous do, the IDE prompted yous for the version of JUnit. You are not prompted to select a version this time because you already selected the JUnit version and all subsequent JUnit tests are created in that version.

You tin can notwithstanding write and run JUnit 3 tests if you select JUnit iv equally the version, but the IDE uses the JUnit 4 template for generating examination skeletons.
  1. Right-click Utils.java and choose Tools > Create Tests.

  2. Select JUnit in the Framework dropdown list if non selected.

  3. Select Test Initializer and Exam Finalizer in the dialog box if not selected.

  4. Alter the name of the exam class to UtilsJUnit4Test in the Create Tests dialog box. Click OK.

When you click OK, the IDE creates the test file UtilsJUnit4Test.java in the Test Packages > sample directory. Yous can see that the IDE generated the test methods testComputeFactorial , testConcatWords , and testNormalizeWord for the methods in Utils.coffee . The IDE also generated initializer and finalizer methods for the examination and the exam class.

Writing Exam Methods for Utils.java

In this practise you will add test cases that illustrate some common JUnit test elements. You will too add together a println to the methods considering some methods practice not print whatsoever output to the JUnit Test Results window to indicate that they were run, or to indicate that the method passed the test. Past calculation a println to the methods y'all can encounter if the methods were run and the club in which they were run.

Examination Initializers and Finalizers

When y'all created the examination class for Utils.java the IDE generated annotated initializer and finalizer methods. You can cull whatever name for the name of the method considering there is no required naming convention.

You do non need the initializer and finalizer methods to exam Utils.coffee , but they are included in this tutorial to demonstrate how they work.

In JUnit 4 you can use annotations to marker the following types of initializer and finalizer methods.

  • Test Class Initializer. The @BeforeClass notation marks a method equally a test class initialization method. A test class initialization method is run only in one case, and before whatsoever of the other methods in the examination class. For example, instead of creating a database connection in a exam initializer and creating a new connection before each examination method, you lot may want to use a test class initializer to open up a connexion before running the tests. You could and so close the connection with the test class finalizer.

  • Examination Class Finalizer. The @AfterClass annotation marks a method as a examination class finalizer method. A test class finalizer method is run only once, and afterwards all of the other methods in the exam class are finished.

  • Test Initializer. The @Before annotation marks a method equally a examination initialization method. A examination initialization method is run before each exam case in the exam class. A examination initialization method is non required to run tests, but if you need to initialize some variables before y'all run a test, you use a exam initializer method.

  • Test Finalizer. The @After note marks a method as a test finalizer method. A test finalizer method is run later on each exam example in the test grade. A test finalizer method is non required to run tests, just you may need a finalizer to make clean up any information that was required when running the examination cases.

Make the following changes (displayed in bold) in UtilsJUnit4Test.java .

                    @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.

Testing Using a Simple Assertion

This simple test example tests the concatWords method. Instead of using the generated test method testConcatWords , yous will add a new test method called helloWorldCheck that uses a single simple assertion to exam if the method concatenates the strings correctly. The assertEquals in the test example uses the syntax assertEquals(EXPECTED_RESULT, ACTUAL_RESULT) to test if the expected result is equal to the actual effect. In this example, if the input to the method concatWords is " Hello ", " , ", " world " and " ! ", the expected issue should equal "Hello, globe!" .

  1. Delete the generated test method testConcatWords .

  2. Add together the following helloWorldCheck method to test Utils.concatWords .@Test public void helloWorldCheck() { assertEquals("Hello, earth!", Utils.concatWords("How-do-you-do", ", ", "world", "!")); }

    1. 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 i - helloWorldCheck()");*     assertEquals("Hello, world!", Utils.concatWords("Howdy", ", ", "world", "!"));                  

Compare: Testing Using a Simple Assertion (JUnit 3)

Testing Using a Timeout

This examination demonstrates how to check if a method is taking too long to complete. If the method is taking too long, the examination thread is interrupted and the test fails. You tin specify the time limit in the exam.

The examination method invokes the computeFactorial method in Utils.java . You can assume that the computeFactorial method is right, but in this instance you want to exam if the computation is completed within 1000 milliseconds. You do this by interrupting the test thread after thousand milliseconds. If the thread is interrupted the examination method throws a TimeoutException .

  1. Delete the generated exam method testComputeFactorial .

  2. Add together 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)); }

    1. Add together the post-obit code (displayed in bold) to gear up the timeout and to interrupt the thread if the method takes likewise long to execute.

                    @Test*(timeout=1000)* public void testWithTimeout() {     concluding int factorialOf = ane + (int) (30000 * Math.random());                  

You lot tin can come across that the timeout is set to 1000 milliseconds.

  1. Add the post-obit println (displayed in bold) to print the text about the examination in the JUnit Test Results window.

                    @Test(timeout=1000) public void testWithTimeout() {     *Organization.out.println("* UtilsJUnit4Test: test method ii - testWithTimeout()");*     last int factorialOf = ane + (int) (30000 * Math.random());     Organization.out.println("computing " + factorialOf + '!');                  

Compare: Testing Using a Timeout (JUnit 3)

Testing for an Expected Exception

This exam demonstrates how to test for an expected exception. The method fails if information technology does non throw the specified expected exception. In this case you are testing that the computeFactorial method throws an IllegalArgumentException if the input variable is a negative number (-5).

  1. Add together the following testExpectedException method that invokes the computeFactorial method with an input of -5.@Test public void checkExpectedException() { concluding int factorialOf = -v; System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); }

    1. Add the following holding (displayed in bold) to the @Test note to specify that the exam is expected to throw IllegalArgumentException .

                    @Test*(expected=IllegalArgumentException.class)* public void checkExpectedException() {     final int factorialOf = -5;     Organisation.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); }                  
  1. Add the following println (displayed in assuming) to impress the text virtually the test in the JUnit Test Results window.

                    @Test (expected=IllegalArgumentException.class) public void checkExpectedException() {     *System.out.println("* UtilsJUnit4Test: examination method 3 - checkExpectedException()");*     final int factorialOf = -v;     System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf)); }                  

Compare: Testing for an Expected Exception (JUnit 3)

Disabling a Exam

This examination demonstrates how to temporarily disable a test method. In JUnit four you simply add the @Ignore note to disable the examination.

  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: examination method iv - checkExpectedException()"); assertEquals("Malm\u00f6", Utils.normalizeWord("Malmo\u0308")); }*

The examination method temporarilyDisabledTest will run if you run the exam class.

  1. Add the @Ignore annotation (displayed in assuming) above @Test to disable the test.@Ignore

                    @Examination public void temporarilyDisabledTest() throws Exception {     Organisation.out.println("* UtilsJUnit4Test: test method 4 - checkExpectedException()");     assertEquals("Malm\u00f6", Utils.normalizeWord("Malmo\u0308")); }                  
  1. Fix your imports to import org.junit.Ignore .

Compare: Disabling a Exam (JUnit 3)

Now that yous accept written the tests you lot can run the test and see the test output in the JUnit Test Results window.

Running the Tests

Y'all tin can run JUnit tests on the unabridged application or on individual files and see the results in the IDE. The easiest way to run all the unit tests for the projection is to cull Run > Test <PROJECT_NAME> from the chief menu. If you lot choose this method, the IDE runs all the exam classes in the Test Packages. To run an individual test class, right-click the examination class under the Test Packages node and cull Run File.

  1. Correct-click UtilsJUnit4Test.java in the Projects window.

  2. Choose Exam File.

  3. Choose Window > IDE Tools > Examination Results to open up the Test Results window.

When you run UtilsJUnit4Test.coffee the IDE just runs the tests in the test course. If the class passes all the tests you will see something similar to the following image in the JUnit Test Results window.

junit4 utilstest pass sm

In this image (click the epitome to see a larger image) you can encounter that the IDE ran the JUnit test on Utils.coffee 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 examination output. If you wait 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 Exam Results window and the Output window.

You can run across that in UtilsJUnit4Test the test class initializer method annotated with @BeforeClass was run before any of the other methods and it was run only in one case. The exam class finalizer method annotated with @AfterClass was run final, afterwards all the other methods in the class. The exam 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 once again. Yous can use the filter to toggle between displaying all test results or merely the failed tests. The arrows enable you to skip to the adjacent 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 exam's source, run the test again or debug the test.

The next step afterwards creating your unit test classes is to create test suites. Meet Creating JUnit four Exam Suites to see how to run specified tests as a group so you practise not have to run each test individually.

Creating Test Suites

When creating tests for a project you lot will generally end upward with many test classes. While you lot can run examination classes individually or run all the tests in a project, in many cases yous will want to run a subset of the tests or run tests in a specific order. You tin can do this by creating one or more test suites. For example, you can create examination suites that test specific aspects of your code or specific conditions.

A test suite is basically a class with a method that invokes the specified test cases, such equally specific test classes, test methods in test classes and other test suites. A test suite can be included as part of a test grade but best practices recommends creating private test suite classes.

You can create JUnit iii and JUnit iv exam suites for your project manually or the IDE can generate the suites for you. When you use the IDE to generate a test suite, by default the IDE generates code to invoke all the test classes in the same package as the test suite. Afterwards the examination suite is created y'all tin modify the grade to specify the tests you want to run as office of that suite.

Creating JUnit 3 Test Suites

If you lot selected JUnit iii as the version for your tests, the IDE can generate JUnit three test suites based on the test classes in the examination package. In JUnit three you lot specify the exam classes to include in the exam suite by creating an instance of TestSuite and using the addTest method for each examination.

  1. Right-click the JUnit-Sample project node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Test Suite in the Unit Tests category. Click Side by side.

  3. Type JUnit3TestSuite for the Class Proper name.

  4. Select the sample package to create the examination suite in the sample binder in the test packages folder.

  5. Deselect Test Initializer and Exam Finalizer. Click Finish.

junit testsuite wizard

When you click Finish, the IDE creates the exam suite class in the sample bundle and opens the class in the editor. The test suite volition contain the post-obit lawmaking.

                  public class JUnit3TestSuite extends TestCase {     public JUnit3TestSuite(String testName) {         super(testName);     }      public static Exam suite() {         TestSuite suite = new TestSuite("JUnit3TestSuite");         return suite;     } }                
  1. Change the suite() method to add the test classes that will be run every bit part of the suite.

                  public JUnit3TestSuite(String testName) {     super(testName); }  public static Examination suite() {     TestSuite suite = new TestSuite("JUnit3TestSuite");     *suite.addTest(new TestSuite(sample.VectorsJUnit3Test.course));     suite.addTest(new TestSuite(sample.UtilsJUnit3Test.form));*     render suite; }                
  1. Relieve your changes.

Creating JUnit 4 Test Suites

If you selected JUnit four for the version of your tests, the IDE tin generate JUnit 4 examination suites. JUnit 4 is back-uniform and then you tin run JUnit 4 examination suites that contain JUnit 4 and JUnit 3 tests. In JUnit 4 test suites you specify the examination classes to include as values of the @Suite annotation.

To run JUnit 3 test suites as role of a JUnit iv test suite requires JUnit 4.4 or higher.
  1. Right-click the project node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Exam Suite in the Unit Tests category. Click Adjacent.

  3. Blazon JUnit4TestSuite for the file name.

  4. Select the sample package to create the test suite in the sample folder in the test packages folder.

  5. Deselect Test Initializer and Test Finalizer. Click Finish.

When you click Terminate, the IDE creates the exam suite class in the sample package and opens the class in the editor. The exam suite contains lawmaking similar to the following.

                  @RunWith(Suite.class) @Suite.SuiteClasses(value={UtilsJUnit4Test.class, VectorsJUnit4Test.class}) public class JUnit4TestSuite { }                

When you run the test suite the IDE will run the test classes in the society that they are listed.

Running Examination Suites

Yous run a test suite the same way you run any individual test grade.

  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.

junit3 suite results sm

In this image (click the prototype to meet a larger epitome) y'all tin see the exam results for a JUnit iii test suite. The test suite ran the UtilsJUnit3Test and VectorsJUnit3Test exam classes as a unmarried test and displayed the exam results in the left pane as the results of a single test. The output in the right pane is the same equally when you run the test individually.

junit4 suite results sm

In this image (click the prototype to run into a larger image) y'all 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 every bit the results of a unmarried test. The output in the right pane is the same as when you lot run the exam individually.

junitmix3and4 suite results sm

In this image (click the image to see a larger epitome) you can see the test results for a mixed test suite. This test suite includes the JUnit 4 test suite and 1 of the JUnit 3 test classes. The test suite ran the UtilsJUnit3Test.coffee and JUnit4TestSuite.java examination classes equally a unmarried 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.

Conclusion

This tutorial has given yous a basic introduction to creating JUnit unit of measurement tests and examination suites in NetBeans IDE. The IDE supports JUnit 3 and JUnit 4, and this certificate demonstrated some of the changes introduced in JUnit 4 that are designed to make creating and running tests simpler.

Equally demonstrated in this tutorial, one of the primary improvements in JUnit 4 is support for annotations. In JUnit four yous tin at present use annotations to practise the following:

  • Place a test using the @Test annotation instead of naming convention

  • Identify setUp and tearDown methods with @Before and @After annotations

  • Place setUp and tearDown methods that apply to the entire examination grade. Methods annotated with @BeforeClass are run but once, earlier any test methods in the course are run. Methods annotated with @AfterClass are also run just in one case, after all the exam methods accept finished.

  • Place expected exceptions

  • Place tests that should be skipped using the @Ignore annotation

  • Specify a timeout parameter for a test

For more than information most using JUnit and other changes introduced in JUnit iv, meet the following resources:

  • JUnit group at Yahoo groups

  • junit.org

Testing code oftentimes helps ensure that minor changes made in the code do not break the application. Automated testing tools similar JUnit streamline the process of testing and frequent testing tin aid catch coding errors early.