Complete understanding of additional classes of JUnit API i.e. TestSuite class, TestCase class, and TestResult class with code examples:
Many of us are not aware of the power that JUnit holds, and it is necessary to know about it as part of JUnit. We already know that TestNG comes with added features when compared with JUnit. However, JUnit 5 is also an amazing framework to use.
So, the choice is always on the script developer as to what he is looking for in a framework and which one fits his needs.
=> Check Out The Perfect JUnit Training Guide Here.
Table of Contents:
JUnit API
In the previous tutorial, we have seen the comparison between TestNG and JUnit.
In the current tutorial, we will go through the JUnit API with a little more depth. In our past tutorials, we have covered a lot on JUnit Annotation, which happens to be a significant API for JUnit, and we will continue to explore more on the annotations in the future tutorials as well.
When we talk about JUnit API, the Assert class is also another prominent entity that shapes the JUnit framework. This topic will be covered later across our upcoming tutorials.
Additional Classes Of JUnit API
As part of additional classes of JUnit API, we will discuss the following:
- TestSuite class: JUnit 3 ; Suite Class for JUnit 4 ; Select Class for JUnit 5.
- TestCase class: JUnit 3
- TestResult class: JUnit 3 and higher.
#1) TestSuite Class
- JUnit 3.8.1 supports the TestSuite Class. This class helps to run multiple test cases.
- The import statement junit.framework.TestSuite helps you include all the functions under TestSuite class.
- You may create an object of class TestSuite and invoke the functions with the test cases through the TestSuite object.
Example:
TestSuite mysuite=new TestSuite(JunitTC.class);
The variations of the TestSuite constructor can be used based on how many classes you wish to pass.
TestSuite Constructor Type | Example |
---|---|
Empty TestSuite Constructor | TestSuite mysuite=new TestSuite(); |
Empty TestSuite Constructor with a name | TestSuite mysuite=new TestSuite(“defaultsuite”); |
Set a testclass to a TestSuite Constructor | TestSuite mysuite=new TestSuite(JUnitTC.class) |
Set a testclass to TestSuite Constructor and set the testsuite name | Testsuite mysuite=new TestSuite(JUnitTC.class, “defaultsuite”); |
The method details are as follows:
Method | Method Detail |
---|---|
void addTest(Test test) | Adds testcase to a suite |
void addTestSuite(java.lang.Class testClass) | State the classname as the input parameter. The Tests under the class will be added to the testsuite |
int testCount() | Returns the number of tests in the suite |
String getName() | gets the Test suite name |
void setName(String value) | Set the Test suite name |
void run(TestResult result) | run the tests and show their results in TestResult |
void runTest(Test test, TestResult result) | runs specific tests and show its result into TestResult |
Test testAt(int index) | returns the test at specific index in the suite |
[reference source]
TestSuites are implemented with a different set of classes in JUnit 4 and JUnit 5.
>> Recommended Reading: “Tutorial 8 JUnit Test Suites & Filtering Testcases”
#2) TestCase Class
- JUnit 3.8.1 supports the TestCase Class. This class helps to create a test case.
- The import statement junit.framework.TestCase helps you include all the functions under TestCase class.
- A test class extends TestCase class. The setUp() function includes the variable initialization and nullifying the variables used inside the tearDown() function.
Alternative 1: The method runTest() is overridden with the method call.
Example:
TestCase tc=new JTestCase1() { public void runTest() { method1();} }; tc.run();
Alternative 2: This way helps to dynamically invoke the test run implicitly through runTest() method.
Example:
TestCase tc=new JTestCase1(“method1”); tc.run ();
The variations of the TestCase constructor are as follows:
TestCase Constructor Type | Example |
---|---|
Empty TestCase Constructor | TestCase(); |
Empty TestCase Constructor with a name | TestCase(“defaulttestcase”); |
The method details for TestCase class are as follows:
Method | Method Detail |
---|---|
int countTestCases() | Gives the number of testcases run by run(TestResult) method |
protected TestResult createResult() | Creates TestResult class object |
String getName() | Get the testcase’s name. |
void setName(String) | Set the name of the testcase. |
protected void setUp() | Variable or any data initialization for the test class is done |
protected void tearDown() | Variable clean up by nullifying the used data is done here. In other words, the resources are released in this function |
Sample Programs for TestSuite and TestCase Class
Here are the Test classes JTestcase1.java and JTestcase2.java. AllTests.java is the TestSuite program that shows up the implementation of most of the applicable methods of TestSuite class.
Code for JTestcase1.java
package junit3; import junit.framework.TestCase; public class JTestCase1 extends TestCase { private int x = 2; private int y = 1; protected void setUp() throws Exception { super.setUp(); } public void testAddition() { int z = x + y; System.out.println("Added number:"+z); } protected void tearDown() throws Exception { super.tearDown(); } }
Output:
Code for JTestcase2.java
package junit3; import junit.framework.TestCase; public class JTestcase2 extends TestCase { private int x = 2; private int y = 1; protected void setUp() throws Exception { super.setUp(); } public void testSubtract() { int z = x - y; System.out.println("Subtracted number:"+z); } protected void tearDown() throws Exception { super.tearDown(); } }
Output:
Code for AllTests.java
package junit3; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { //TestSuite constructor with a name added as a parameter TestSuite suite = new TestSuite(AllTests.class,"mysuite"); //Test classes added to the suite with addTestSuite() suite.addTestSuite(JTestcase1.class); suite.addTestSuite(JTestcase2.class); //testAt(int) System.out.println("Testclass at index 1 : suite.testAt(1)"+suite.testAt(1)); //testCount() System.out.println("Number of testcases under the suite :suite.testCount() :"+suite.testCount()); System.out.println("Number of testcases under a JTestcase1 testclass :testclass.countTestCase() :"+new JTestcase1().countTestCases()); //getName() System.out.println("Name of the suite : suite.getName() :"+suite.getName()); //setName() suite.setName("oursuite"); System.out.println("New name of the suite : suite.getName() :"+suite.getName()); return suite; }}
Output:
#3) TestResult Class
The TestResult class captures the execution status, including failures and errors of the test cases.
Failures could be the failed resultant of an assertion applied in the testcase, whereas Errors are unexpected Errors/Exceptions like NumberFormatException.
Method | Method Detail |
---|---|
void addError(Test test, java.lang.Throwable t) | Adds an error to the list of Errors |
void addFailure(Test test, AssertionFailedError t) | Add a failure to the failures list |
void addListener(TestListener listener) | Registers a TestListener |
void endTest(Test test) | Results into testcase completion. |
int errorCount() | Gets number of detected errors |
int failureCount() | Gets number of detected failures |
void removeListener(TestListener listener) | Unregisters a TestListener |
protected void run(TestCase test) | Runs a specific testcase |
int runCount() | Fetches the number of test executed |
void startTest(Test test) | Starts the test execution |
void stop() | Stops the test execution |
boolean wasSuccessful() | Returns true or false based on the final test execution status |
Sample Programs for TestResult Class: JUnit 3
Here, JTestCase1.java shows the detailed implementation of TestResult class and its methods.
This is how we implement TestResult Class with JUnit 3 (3.8.1 is the version of JUnit I have used)
Code for JTestcase1.java
package junit3; import junit.framework.TestCase; import junit.framework.TestResult; public class JTestcase1 extends TestCase { int x = 2; int y = 3; TestResult result; protected void setUp() throws Exception { super.setUp(); } public void testAddition() throws AssertionError { int z = x+y; } //TestResult result public void run(TestResult result) { if (result.wasSuccessful()) { System.out.println("Test Results when Test passed"); System.out.println("RunCount: " + result.runCount()); System.out.println("FailureCount: " + result.failureCount()); System.out.println("ErrorCount: " + result.errorCount()); } else { System.out.println("Test Results when Test failed"); System.out.println("RunCount: " + result.runCount()); System.out.println("FailureCount: " + result.failureCount()); System.out.println("ErrorCount: " + result.errorCount()); } } protected void tearDown() throws Exception { super.tearDown(); } }
Output:
Sample Programs for TestResult Class: JUnit 4
Here, we will see the implementation of TestResult Class for JUnit 4 (4.12 is the version of JUnit I have used). The sample program includes the Junit4TestResultClass.java which will result in failure of the assertion.
The class extends TestResult class and implements its methods addError() and stop(). Another java class- Runner.java will fetch results for execution of Junit4TestResultClass through methods under org.junit.runner.JUnitCore, org.junit.runner.Result, org.junit.runner.notification.Failure.
Code for Junit4TestResultClass.java
package junit4; import org.junit.Assert; import org.junit.Test; import junit.framework.TestResult; public class Junit4TestResultClass extends TestResult{ int x=3; int y=2; //add errors public synchronized void addError(Test test, Throwable t) { super.addError((junit.framework.Test)test,t); } @Test public void testSubtract() { try { int z = x - y; //System.out.println("Subtracted number:"+z); Assert.assertEquals(z,2); } catch(Exception e) { System.out.println(e.getMessage()); } } public synchronized void stop() { System.out.println("Test stopped"); } }
Output:
Code for Runner.java
package junit4; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class Runner { public static void main(String[] args) { Result result=JUnitCore.runClasses(Junit4TestResultClass.class); for(Failure failure:result.getFailures()) { System.out.println(failure.toString()); } System.out.println("Result is Successful -true or false? :"+result.wasSuccessful()); if(result.wasSuccessful()) { System.out.println("----------------------------------------"); System.out.println("Test Results when Test passed"); System.out.println("RunCount: " + result.getRunCount()); System.out.println("FailureCount: " + result.getFailureCount()); } else { System.out.println("----------------------------------------"); System.out.println("Test Results when Test failed"); System.out.println("RunCount: " + result.getRunCount()); System.out.println("FailureCount: " + result.getFailureCount()); } System.out.println("----------------------------------------"); } }
Output:
Conclusion
In this tutorial, we have learned more about the additional classes that JUnit focuses on, i.e. TestCase, TestResult, TestSuite class. Prominently we saw that we can use these TestCase and TestSuite classes in JUnit 3. TestResult class can be used in any version of JUnit starting from Junit 3 and higher.
We also saw the implementation of TestResult class in both JUnit3 and JUnit 4.
So, this is it for this tutorial. We will come back with many more interesting aspects of JUnit in our future tutorials.
Keep Learning!!!