Using Testing Frameworks
While you could write your own testing classes, you’re generally better off utilizing a testing framework. There are a number to choose from to test Java programs and classes. Some of the most popular frameworks include JUnit, Selenium, and TestNG.
The major benefit of using a framework is that it already contains a set of methods and annotations that make writing tests easier. Instead of rewriting conditionals for passing or failing a test, implementing a counter for passed versus failed test cases, or setting up complicated control flow scenarios to test for exceptions, the testing framework already provides these things. You simply write your test methods, run the main method, and the test library takes care of executing your test methods, tallying the passes and failures, and handling exceptions. The driver program discovers and run the unit tests. This helps ensure that tests are run in a consistent manner with consistent output.
For this course, we will use TestNG.
TestNG Basics
The following sections will introduce example TestNG tests, but here’s the basic gist. You do not need a main method; you simply write the test methods. How to run the tests depends on your development environment. Most IDE’s have a testing plug-in that allows you to run the tests using the GUI. The next section explains how to run the tests using Gradle and VSCode.
Below is a very simple test file that demonstrates the basic use case.
/* * Simple TestNG example tests */ /*Import the required annotations (like @Test) and assert methods */ import org.testng.annotations.*; import static org.testng.Assert.*; // Declare a class as your test class public class MainTest { /* * Each test method must be annotated with @Test to be run as a test method. * You can have other methods in your test file, but only those marked * with @Test * Will be run and tallied in the test results */ /* * test methods are generally named starting with test and describe * what is being tested */ @Test public void testGetAge() { int expectedAge = 4; ClassToBeTested testObject = new ClassToBeTested(expectedAge); // Checks that the return value of getAge is equal // to the value of expectedValue // assertEquals ( actual, expected) assertEquals(testObject.getAge(), expectedAge); /* * * There are a number of overloaded assertEquals methods. Check out the TestNG * documentation linked at the end of this section for a complete list. * */ } /** * Verifies that Java.String’s length method works correctly */ @Test public void testStringLength() { String testObj = "how long would this be"; int expectedLength = 22; assertEquals(testObj.length(), expectedLength); } }