30 min read

In this article by David Salter, the author of Mastering NetBeans, we’ll cover the following topics:

  • Running applications
  • Debugging applications
  • Profiling applications
  • Testing applications

On a day-to-day basis, developers spend much of their time writing and running applications. While writing applications, they typically debug, test, and profile them to ensure that they provide the best possible application to customers. Running, debugging, profiling, and testing are all integral parts of the development life cycle, and NetBeans provides excellent tooling to help us in all these areas.

(For more resources related to this topic, see here.)

Running applications

Executing applications from within NetBeans is as simple as either pressing the F6 button on the keyboard or selecting the Run menu item or Project Context menu item. Choosing either of these options will launch your application without specifying any additional Java command-line parameters using the default platform JDK that NetBeans is currently using.


Sometimes we want to change the options that are used for launching applications. NetBeans allows these options to be easily specified by a project’s properties.

Right-clicking on a project in the Projects window and selecting the Properties menu option opens the Project Properties dialog. Selecting the Run category allows the configuration options to be defined for launching an application.

Mastering NetBeans

From this dialog, we can define and select multiple run configurations for the project via the Configuration dropdown. Selecting the New… button to the right of the Configuration dropdown allows us to enter a name for a new configuration. Once a new configuration is created, it is automatically selected as the active configuration. The Delete button can be used for removing any unwanted configurations.

The preceding screenshot shows the Project Properties dialog for a standard Java project. Different project types (for example, web or mobile projects) have different options in the Project Properties window.

As can be seen from the preceding Project Properties dialog, several pieces of information can be defined for a standard Java project, which together make up the launch configuration for a project:

  • Runtime Platform: This option allows us to define which Java platform we will use when launching the application. From here, we can select from all the Java platforms that are configured within NetBeans. Selecting the Manage Platforms… button opens the Java Platform Manager dialog, allowing full configuration of the different Java platforms available (both Java Standard Edition and Remote Java Standard Edition). Selecting this button has the same effect as selecting the Tools and then Java Platforms menu options.
  • Main Class: This option defines the main class that is used to launch the application. If the project has more than one main class, selecting the Browse… button will cause the Browse Main Classes dialog to be displayed, listing all the main classes defined in the project.
  • Arguments: Different command-line arguments can be passed to the main class as defined in this option.
  • Working Directory: This option allows the working directory for the application to be specified.
  • VM Options: If different VM options (such as heap size) require setting, they can be specified by this option. Selecting the Customize button displays a dialog listing the different standard VM options available which can be selected (ticked) as required. Custom VM properties can also be defined in the dialog.

    Mastering NetBeans

    For more information on the different VM properties for Java, check out http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html. From here, the VM properties for Java 7 (and earlier versions) and Java 8 for Windows, Solaris, Linux, and Mac OS X can be referenced.

  • Run with Java Web Start: Selecting this option allows the application to be executed using Java Web Start technologies. This option is only available if Web Start is enabled in the Application | Web Start category.

    Mastering NetBeans

When running a web application, the project properties are different from those of a standalone Java application. In fact, the project properties for a Maven web application are different from those of a standard NetBeans web application. The following screenshot shows the properties for a Maven-based web application; as discussed previously, Maven is the standard project management tool for Java applications, and the recommended tool for creating and managing web applications:

Mastering NetBeans

Debugging applications

In the previous section, we saw how NetBeans provides the easy-to-use features to allow developers to launch their applications, but then it also provides more powerful additional features. The same is true for debugging applications.

For simple debugging, NetBeans provides the standard facilities you would expect, such as stepping into or over methods, setting line breakpoints, and monitoring the values of variables.

When debugging applications, NetBeans provides several different windows, enabling different types of information to be displayed and manipulated by the developer:

  • Breakpoints
  • Variables
  • Call stack
  • Loaded classes
  • Sessions
  • Threads
  • Sources
  • Debugging
  • Analyze stack

All of these windows are accessible from the Window and then Debugging main menu within NetBeans.

Breakpoints

NetBeans provides a simple approach to set breakpoints and a more comprehensive approach that provides many more useful features.

Breakpoints can be easily added into Java source code by clicking on the gutter on the left-hand side of a line of Java source code. When a breakpoint is set, a small pink square is shown in the gutter and the entire line of source code is also highlighted in the same color. Clicking on the breakpoint square in the gutter toggles the breakpoint on and off.

Mastering NetBeans

Once a breakpoint has been created, instead of removing it altogether, it can be disabled by right-clicking on the bookmark in the gutter and selecting the Breakpoint and then Enabled menu options. This has the effect of keeping the breakpoint within your codebase, but execution of the application does not stop when the breakpoint is hit.

Creating a simple breakpoint like this can be a very powerful way of debugging applications. It allows you to stop the execution of an application when a line of code is hit.

If we want to add a bit more control onto a simple breakpoint, we can edit the breakpoint’s properties by right-clicking on the breakpoint in the gutter and selecting the Breakpoint and then Properties menu options. This causes the Breakpoint Properties dialog to be displayed:

Mastering NetBeans

In this dialog, we can see the line number and the file that the breakpoint belongs to. The line number can be edited to move the breakpoint if it has been created on the wrong line. However, what’s more interesting is the conditions that we can apply to the breakpoint.

The Condition entry allows us to define a condition that has to be met for the breakpoint to stop the code execution. For example, we can stop the code when the variable i is equal to 20 by adding a condition, i==20.

When we add conditions to a breakpoint, the breakpoint becomes known as a conditional breakpoint, and the icon in the gutter changes to a square with the lower-right quadrant removed.

Mastering NetBeans

We can also cause the execution of the application to halt at a breakpoint when the breakpoint has been hit a certain number of times. The Break when hit count is condition can be set to Equal to, Greater than, or Multiple of to halt the execution of the application when the breakpoint has been hit the requisite number of times.

Finally, we can specify what actions occur when a breakpoint is hit. The Suspend dropdown allows us to define what threads are suspended when a breakpoint is hit. NetBeans can suspend All threads, Breakpoint thread, or no threads at all. The text that is displayed in the Output window can be defined via the Print Text edit box and different breakpoint groups can be enabled or disabled via the Enable Group and Disable Group drop-down boxes. But what exactly is a breakpoint group?

Simply put, a breakpoint group is a collection of breakpoints that can all be set or unset at the same time. It is a way of categorizing breakpoints into similar collections, for example, all the breakpoints in a particular file, or all the breakpoints relating to exceptions or unit tests.

Breakpoint groups are created in the Breakpoints window. This is accessible by selecting the Debugging and then Breakpoints menu options from within the main NetBeans Window menu.

Mastering NetBeans

To create a new breakpoint group, simply right-click on an existing breakpoint in the Breakpoints window and select the Move Into Group… and then New… menu options.

Mastering NetBeans

The Set the Name of Breakpoints Group dialog is displayed in which the name of the new breakpoint group can be entered.

After creating a breakpoint group and assigning one or more breakpoints into it, the entire group of breakpoints can be enabled or disabled, or even deleted by right-clicking on the group in the Breakpoints window and selecting the appropriate option.

Any newly created breakpoint groups will also be available in the Breakpoint Properties window.

So far, we’ve seen how to create breakpoints that stop on a single line of code, and also how to create conditional breakpoints so that we can cause an application to stop when certain conditions occur for a breakpoint. These are excellent techniques to help debug applications. NetBeans, however, also provides the ability to create more advanced breakpoints so that we can get even more control of when the execution of applications is halted by breakpoints.

So, how do we create these breakpoints? These different types of breakpoints are all created from in the Breakpoints window by right-clicking and selecting the New Breakpoint… menu option.

Mastering NetBeans

In the New Breakpoint dialog, we can create different types of breakpoints by selecting the appropriate entry from the Breakpoint Type drop-down list. The preceding screenshot shows an example of creating a Class breakpoint. The following types of breakpoints can be created:

  • Class: This creates a breakpoint that halts execution when a class is loaded, unloaded, or either event occurs.
  • Exception: This stops execution when the specified exception is caught, uncaught, or either event occurs.
  • Field: This creates a breakpoint that halts execution when a field on a class is accessed, modified, or either event occurs.
  • Line: This stops execution when the specified line of code is executed. It acts the same way as creating a breakpoint by clicking on the gutter of the Java source code editor window.
  • Method: This creates a breakpoint that halts execution when a method is entered, exited, or when either event occurs. Optionally, the breakpoint can be created for all methods inside a specified class rather than a single method.
  • Thread: This creates a breakpoint that stops execution when a thread is started, finished, or either event occurs.
  • AWT/Swing Component: This creates a breakpoint that stops execution when a GUI component is accessed.

For each of these different types of breakpoints, conditions and actions can be specified in the same way as on simple line-based breakpoints.

The Variables debug window

The Variables debug window lists all the variables that are currently within  the scope of execution of the application. This is therefore thread-specific, so if multiple threads are running at one time, the Variables window will only display variables in scope for the currently selected thread.

In the Variables window, we can see the variables currently in scope for the selected thread, their type, and value.

Mastering NetBeans

To display variables for a different thread to that currently selected, we must select an alternative thread via the Debugging window.

Using the triangle button to the left of each variable, we can expand variables and drill down into the properties within them.

When a variable is a simple primitive (for example, integers or strings), we can modify it or any property within it by altering the value in the Value column in the Variables window. The variable’s value will then be changed within the running application to the newly entered value.

By default, the Variables window shows three columns (Name, Type, and Value). We can modify which columns are visible by pressing the selection icon (Mastering NetBeans) at the top-right of the window.

Selecting this displays the Change Visible Columns dialog, from which we can select from the Name, String value, Type, and Value columns:

Mastering NetBeans

The Watches window

The Watches window allows us to see the contents of variables and expressions during a debugging session, as can be seen in the following screenshot:

Mastering NetBeans

In this screenshot, we can see that the variable i is being displayed along with the expressions 10+10 and i+20.

New expressions can be watched by clicking on the option or by right-clicking on the Java source code editor and selecting the New Watch… menu option.

Evaluating expressions

In addition to watching variables in a debugging session, NetBeans also provides the facility to evaluate expressions. Expressions can contain any Java code that is valid for the running scope of the application. So, for example, local variables, class variables, or new instances of classes can be evaluated.

To evaluate variables, open the Evaluate Expression window by selecting the Debug and then Evaluate Expression menu options.

Mastering NetBeans

Enter an expression to be evaluated in this window and press the Evaluate Code Fragment button at the bottom-right corner of the window. As a shortcut, pressing the Ctrl + Enter keys will also evaluate the code fragment.

Once an expression has been evaluated, it is shown in the Evaluation Result window. The Evaluation Result window shows a history of each expression that has previously been evaluated. Expressions can be added to the list of watched variables by right-clicking on the expression and selecting the Create Fixed Watch expression.

The Call Stack window

The Call Stack window displays the call stack for the currently executing thread:

Mastering NetBeans

The call stack is displayed from top to bottom with the currently executing frame at the top of the list. Double-clicking on any entry in the call stack opens up the corresponding source code in the Java editor within NetBeans.

Right-clicking on an entry in the call stack displays a pop-up menu with the choice to:

  • Make Current: This makes the selected thread the current thread
  • Pop To Here: This pops the execution of the call stack to the selected location
  • Go To Source: This displays the selected code within the Java source editor
  • Copy Stack: This copies the stack trace to the clipboard for use elsewhere

When debugging, it can be useful to change the stack frame of the currently executing thread by selecting the Pop To Here option from within the stack trace window. Imagine the following code:

// Get some magic

int magic = getSomeMagicNumber();

// Perform calculation

performCalculation(magic);

During a debugging session, if after stepping over the getSomeMagicNumber() method, we decided that the method has not worked as expected, our course of action would probably be to debug into the getSomeMagicNumber() method. But, we’ve just stepped over the method, so what can we do? Well, we can stop the debugging session and start again or repeat the operation that called this section of code and hope there are no changes to the application state that affect the method we want to debug.

A better solution, however, would be to select the line of code that calls the getSomeMagicNumber() method and pop the stack frame using the Pop To Here option. This would have the effect of rewinding the code execution so that we can then step into the method and see what is happening inside it.

As well as using the Pop To Here functionality, NetBeans also offers several menu options for manipulating the stack frame, namely:

  • Make Callee Current: This makes the callee of the current method the currently executing stack frame
  • Make Caller Current: This makes the caller of the current method the currently executing stack frame
  • Pop Topmost Call: This pops one stack frame, making the calling method the currently executing stack frame

When moving around the call stack using these techniques, any operations performed by the currently executing method are not undone. So, for example, strange results may be seen if global or class-based variables are altered within a method and then an entry is popped from the call stack. Popping entries in the call stack is safest when no state changes are made within a method.

The call stack displayed in the Debugging window for each thread behaves in the same way as in the Call Stack window itself.

The Loaded Classes window

The Loaded Classes window displays a list of all the classes that are currently loaded, showing how many instances there are of each class as a number and as a percentage of the total number of classes loaded.

Mastering NetBeans

Depending upon the number of external libraries (including the standard Java runtime libraries) being used, you may find it difficult to locate instances of your own classes in this window. Fortunately, the filter at the bottom of the window allows the list of classes to be filtered, based upon an entered string. So, for example, entering the filter String will show all the classes with String in the fully qualified class name that are currently loaded, including java.lang.String and java.lang.StringBuffer. Since the filter works on the fully qualified name of a class, entering a package name will show all the classes listed in that package and subpackages. So, for example, entering a filter value as com.davidsalter.multithread would show only the classes listed in that package and subpackages.

The Sessions window

Within NetBeans, it is possible to perform multiple debugging sessions where either one project is being debugged multiple times, or more commonly, multiple projects are being debugged at the same time, where one is acting as a client application and the other is acting as a server application.

The Sessions window displays a list of the currently running debug sessions, allowing the developer control over which one is the current session. Right-clicking on any of the sessions listed in the window provides the following options:

  • Make Current: This makes the selected session the currently active debugging session
  • Scope: This debugs the current thread or all the threads in the selected session
  • Language: This options shows the language of the application being debugged—Java
  • Finish: This finishes the selected debugging session
  • Finish All: This finishes all the debugging sessions

The Sessions window shows the name of the debug session (for example the main class being executed), its state (whether the application is Stopped or Running) and language being debugged. Clicking the selection icon (Mastering NetBeans) at the top-right of the window allows the user to choose which columns are displayed in the window.

Mastering NetBeans

The default choice is to display all columns except for the Host Name column, which displays the name of the computer the session is running on.

The Threads window

The Threads window displays a hierarchical list of threads in use by the application currently being debugged.

Mastering NetBeans

The current thread is displayed in bold. Double-clicking on any of the threads in the hierarchy makes the thread current. Similar to the Debugging window, threads can be made current, suspended, or interrupted by right-clicking on the thread and selecting the appropriate option.

The default display for the Threads window is to show the thread’s name and its state (Running, Waiting, or Sleeping). Clicking the selection icon (Mastering NetBeans) at the top-right of the window allows the user to choose which columns are displayed in the window.

Mastering NetBeans

The Sources window

The Sources window simply lists all of the source roots that NetBeans considers for the selected project. These are the only locations that NetBeans will search when looking for source code while debugging an application. If you find that you are debugging an application, and you cannot step into code, the most likely scenario is that the source root for the code you wish to debug is not included in the Sources window. To add a new source root, right-click in the Sources window and select the Add Source Root option.

Mastering NetBeans

The Debugging window

The Debugging window allows us to see which threads are running while debugging our application. This window is, therefore, particularly useful when debugging multithreaded applications.

Mastering NetBeans

In this window, we can see the different threads that are running within our application. For each thread, we can see the name of the thread and the call stack leading to the breakpoint. The current thread is highlighted with a green band along the left-hand side edge of the window. Other threads created within our application are denoted with a yellow band along the left-hand side edge of the window. System threads are denoted with a gray band.

We can make any of the threads the current thread by right-clicking on it and selecting the Make Current menu option. When we do this, the Variables and Call Stack windows are updated to show new information for the selected thread.

The current thread can also be selected by clicking on the Debug and then Set Current Thread… menu options. Upon selecting this, a list of running threads is shown from which the current thread can be selected.

Right-clicking on a thread and selecting the Resume option will cause the selected thread to continue execution until it hits another breakpoint.

For each thread that is running, we can also Suspend, Interrupt, and Resume the thread by right-clicking on the thread and choosing the appropriate action.

In each thread listing, the current methods call stack is displayed for each thread. This can be manipulated in the same way as from the Call Stack window.

When debugging multithreaded applications, new breakpoints can be hit within different threads at any time. NetBeans helps us with multithreaded debugging by not automatically switching the user interface to a different thread when a breakpoint is hit on the non-current thread. When a breakpoint is hit on any thread other than the current thread, an indication is displayed at the bottom of the Debugging window, stating New Breakpoint Hit (an example of this can be seen in the previous window). Clicking on the icon to the right of the message shows all the breakpoints that have been hit together with the thread name in which they occur. Selecting the alternate thread will cause the relevant breakpoint to be opened within NetBeans and highlighted in the appropriate Java source code file.

NetBeans provides several filters on the Debugging window so that we can show more/less information as appropriate.

Mastering NetBeans

From left to right, these images allow us to:

  • Show less (suspended and current threads only)
  • Show thread groups
  • Show suspend/resume table
  • Show system threads
  • Show monitors
  • Show qualified names
  • Sort by suspended/resumed state
  • Sort by name
  • Sort by default

Debugging multithreaded applications can be a lot easier if you give your threads names. The thread’s name is displayed in the Debugging window, and it’s a lot easier to understand what a thread with a proper name is doing as opposed to a thread called Thread-1.

Deadlock detection

When debugging multithreaded applications, one of the problems that we can see is that a deadlock occurs between executing threads. A deadlock occurs when two or more threads become blocked forever because they are both waiting for a shared resource to become available. In Java, this typically occurs when the synchronized keyword is used.

NetBeans allows us to easily check for deadlocks using the Check for Deadlock tool available on the Debug menu.

When a deadlock is detected using this tool, the state of the deadlocked threads is set to On Monitor in the Threads window. Additionally, the threads are marked as deadlocked in the Debugging window. Each deadlocked thread is displayed with a red band on the left-hand side border and the Deadlock detected warning message is displayed.

Mastering NetBeans

Analyze Stack Window

When running an application within NetBeans, if an exception is thrown and not caught, the stack trace will be displayed in the Output window, allowing the developer to see exactly where errors have occurred. From the following screenshot, we can easily see that a NullPointerException was thrown from within the FaultyImplementation class in the doUntestedOperation() method at line 16. Looking before this in the stack trace (that is the entry underneath), we can see that the doUntestedOperation() method was called from within the main() method of the Main class at line 21:

Mastering NetBeans

In the preceding example, the FaultyImplementation class is defined as follows:

public class FaultyImplementation {

    public void doUntestedOperation() {

        throw new NullPointerException();

    }

}

Java is providing an invaluable feature to developers, allowing us to easily see where exceptions are thrown and what the sequence of events was that led to the exception being thrown. NetBeans, however, enhances the display of the stack traces by making the class and line numbers clickable hyperlinks which, when clicked on, will navigate to the appropriate line in the code. This allows us to easily delve into a stack trace and view the code at all the levels of the stack trace. In the previous screenshot, we can click on the hyperlinks FaultyImplementation.java:16 and Main.java:21 to take us to the appropriate line in the appropriate Java file.

This is an excellent time-saving feature when developing applications, but what do we do when someone e-mails us a stack trace to look at an error in a production system? How do we manage stack traces that are stored in log files?

Fortunately, NetBeans provides an easy way to allow a stack trace to be turned into clickable hyperlinks so that we can browse through the stack trace without running the application.

To load and manage stack traces into NetBeans, the first step is to copy the stack trace onto the system clipboard. Once the stack trace has been copied onto the clipboard, Analyze Stack Window can be opened within NetBeans by selecting the Window and then Debugging and then Analyze Stack menu options (the default installation for NetBeans has no keyboard shortcut assigned to this operation).

Mastering NetBeans

Analyze Stack Window will default to showing the stack trace that is currently in the system clipboard. If no stack trace is in the clipboard, or any other data is in the system’s clipboard, Analyze Stack Window will be displayed with no contents. To populate the window, copy a stack trace into the system’s clipboard and select the Insert StackTrace From Clipboard button.

Once a stack trace has been displayed in Analyze Stack Window, clicking on the hyperlinks in it will navigate to the appropriate location in the Java source files just as it does from the Output window when an exception is thrown from a running application.

You can only navigate to source code from a stack trace if the project containing the relevant source code is open in the selected project group.

Variable formatters

When debugging an application, the NetBeans debugger can display the values of simple primitives in the Variables window. As we saw previously, we can also display the toString() representation of a variable if we select the appropriate columns to display in the window.

Sometimes when debugging, however, the toString() representation is not the best way to display formatted information in the Variables window.

Mastering NetBeans

In this window, we are showing the value of a complex number class that we have used in high school math. The ComplexNumber class being debugged in this example is defined as:

public class ComplexNumber {

 

    private double realPart;

    private double imaginaryPart;

 

    public ComplexNumber(double realPart, double imaginaryPart) {

        this.realPart = realPart;

        this.imaginaryPart = imaginaryPart;

    }

 

    @Override

    public String toString() {

        return "ComplexNumber{" + "realPart=" + realPart + ", imaginaryPart=" + imaginaryPart + '}';

    }

 

  // Getters and Setters omitted for brevity…

 

}

Looking at this class, we can see that it essentially holds two members—realPart and imaginaryPart. The toString() method outputs a string, detailing the name of the object and its parameters which would be very useful when writing ComplexNumbers to log files, for example:

ComplexNumber{realPart=1.0, imaginaryPart=2.0}

When debugging, however, this is a fairly complicated string to look at and comprehend—particularly, when there is a lot of debugging information being displayed.

NetBeans, however, allows us to define custom formatters for classes that detail how an object will be displayed in the Variables window when being debugged.

To define a custom formatter, select the Java option from the NetBeans Options dialog and then select the Java Debugger tab. From this tab, select the Variable Formatters category.

Mastering NetBeans

On this screen, all the variable formatters that are defined within NetBeans are shown. To create a new variable formatter, select the Add… button to display the Add Variable Formatter dialog.

Mastering NetBeans

In the Add Variable Formatter dialog, we need to enter Formatter Name and a list of Class types that NetBeans will apply the formatting to when displaying values in the debugger. To apply the formatter to multiple classes, enter the different classes, separated by commas.

The value that is to be formatted is entered in the Value formatted as a result of code snippet field. This field takes the scope of the object being debugged. So, for example, to output the ComplexNumber class, we can enter the custom formatter as:

"("+realPart+", "+imaginaryPart+"i)"

We can see that the formatter is built up from concatenating static strings and the values of the members realPart and imaginaryPart.

We can see the results of debugging variables using custom formatters in the following screenshot:

Mastering NetBeans

Debugging remote applications

The NetBeans debugger provides rapid access for debugging local applications that are executing within the same JVM as NetBeans.

What happens though when we want to debug a remote application? A remote application isn’t necessarily hosted on a separate server to your development machine, but is defined as any application running outside of the local JVM (that is the one that is running NetBeans).

To debug a remote application, the NetBeans debugger can be “attached” to the remote application. Then, to all intents, the application can be debugged in exactly the same way as a local application is debugged, as described in the previous sections of this article.

To attach to a remote application, select the Debug and then Attach Debugger… menu options.

Mastering NetBeans

On the Attach dialog, the connector (SocketAttach, ProcessAttach, or SocketListen) must be specified to connect to the remote application. The appropriate connection details must then be entered to attach the debugger. For example, the process ID must be entered for the ProcessAttach connector and the host and port must be specified for the SocketAttach connector.

Profiling applications

Learning how to debug applications is an essential technique in software development. Another essential technique that is often overlooked is profiling applications.

Profiling applications involves measuring various metrics such as the amount of heap memory used or the number of loaded classes or running threads. By profiling applications, we can gain an understanding of what our applications are actually doing and as such we can optimize them and make them function better. NetBeans provides first class profiling tools that are easy to use and provide results that are easy to interpret. The NetBeans profiler allows us to profile three specific areas:

  • Application monitoring
  • Performance monitoring
  • Memory monitoring

Each of these monitoring tools is accessible from the Profile menu within NetBeans. To commence profiling, select the Profile and then Profile Project menu options. After instructing NetBeans to profile a project, the profiler starts providing the choice of the type of profiling to perform.

Testing applications

Writing tests for applications is probably one of the most important aspects of modern software development. NetBeans provides the facility to write and run both JUnit and TestNG tests and test suites. In this section, we’ll provide details on how NetBeans allows us to write and run these types of tests, but we’ll assume that you have some knowledge of either JUnit or TestNG.

TestNG support is provided by default with NetBeans, however, due to license concerns, JUnit may not have been installed when you installed NetBeans. If JUnit support is not installed, it can easily be added through the NetBeans Plugins system.

In a project, NetBeans creates two separate source roots: one for application sources and the other for test sources. This allows us to keep tests separate from application source code so that when we ship applications, we do not need to ship tests with them.

This separation of application source code and test source code enables us to write better tests and have less coupling between tests and applications. The best situation is for the test source root to have a dependency on application classes and the application classes to have no dependency on the tests that we have written.

Mastering NetBeans

To write a test, we must first have a project. Any type of Java project can have tests added into it. To add tests into a project, we can use the New File wizard. In the Unit Tests category, there are templates for:

  • JUnit Tests
  • Tests for Existing Class (this is for JUnit tests)
  • Test Suite (this is for JUnit tests)
  • TestNG Test Case
  • TestNG Test Suite

Mastering NetBeans

When creating classes for these types of tests, NetBeans provides the option to automatically generate code; this is usually a good starting point for writing classes.

Mastering NetBeans

When executing tests, NetBeans iterates through the test packages in a project looking for the classes that are suffixed with the word Test. It is therefore essential to properly name tests to ensure they are executed correctly.

Once tests have been created, NetBeans provides several methods for running the tests. The first method is to run all the tests that we have defined for an application. Selecting the Run and then Test Project menu options runs all of the tests defined for a project. The type of the project doesn’t matter (Java SE or Java EE), nor whether a project uses Maven or the NetBeans project build system (Ant projects are even supported if they have a valid test activity), all tests for the project will be run when selecting this option.

After running the tests, the Test Results window will be displayed, highlighting successful tests in green and failed tests in red.

Mastering NetBeans

In the Test Results window, we have several options to help categorize and manage the tests:

  • Rerun all of the tests
  • Rerun the failed tests
  • Show only the passed tests
  • Show only the failed tests
  • Show errors
  • Show aborted tests
  • Show skipped tests
  • Locate previous failure
  • Locate next failure
  • Always open test result window
  • Always open test results in a new tab

The second option within NetBeans for running tests it to run all the tests in a package or class. To perform these operations, simply right-click on a package in the Projects window and select Test Package or right-click on a Java class in the Projects window and select Test File.

The final option for running tests it to execute a single test in a class. To perform this operation, right-click on a test in the Java source code editor and select the Run Focussed Test Method menu option.

After creating tests, how do we keep them up to date when we add new methods to application code? We can keep tests suites up to date by manually editing them and adding new methods corresponding to new application code or we can use the Create/Update Tests menu. Selecting the Tools and then Create/Update Tests menu options displays the Create Tests dialog that allows us to edit the existing test classes and add new methods into them, based upon the existing application classes.

Mastering NetBeans

Summary

In this article, we looked at the typical tasks that a developer does on a day-to-day basis when writing applications. We saw how NetBeans can help us to run and debug applications and how to profile applications and write tests for them. Finally, we took a brief look at TDD, and saw how the Red-Green-Refactor cycle can be used to help us develop more stable applications.

Resources for Article:


Further resources on this subject:



Subscribe to the weekly Packt Hub newsletter. We'll send you the results of our AI Now Survey, featuring data and insights from across the tech landscape.

LEAVE A REPLY

Please enter your comment!
Please enter your name here