Writing unit tests is a part of good practice in software development. Maven's test
phase executes unit tests and generates the corresponding report. In this section, we will learn about writing a simple unit test for our utility class ConversionUtil
, and in the next section, we will see how to execute it and generate reports.
All the unit test classes should go under src/test/java
. Create the corresponding folder in the MyDistance
project. Once the folder is in place, right-click on it and navigate to New | Other.... Once the wizard window appears, type in junit
in the Filter section, select JUnit Test Case, and click on Next, as shown in the following screenshot:
In the window to follow, define the unit test class by filling in the following details and click on Next, as shown in the preceding screenshot:
Fields |
Values |
---|---|
Source folder |
|
Package |
|
Name |
|
Class under test |
|
A window to choose test methods will be shown, for which stubs will be generated as shown in the following screenshot. Make sure that all methods of the ConversionUtil
class are checked and click on Finish as follows:
The ConversionUtilTest
test class with the test method stubs will be generated. Edit the code of the class as follows:
private ConversionUtil conversion; @Override protected void setUp() throws Exception { super.setUp(); conversion= new ConversionUtil(); } public void testConvertKmToMile() { double actual=conversion.convertKMToMile(4); assertEquals(2.48548,actual,0.001); } public void testConvertkmToYard() { double actual=conversion.convertkmToYard(4); assertEquals(4374.45,actual,0.10); } public void testConvertMToMile() { double actual=conversion.convertMToMile(4000); assertEquals(2.48548,actual,0.001); } public void testConvertMtoYard() { double actual=conversion.convertMtoYard(4000); assertEquals(4374.45,actual,0.10); } @Override protected void tearDown() throws Exception { super.tearDown(); conversion = null; }
For more information on JUnit test cases, refer to http://junit.org/.
18.191.254.44