Lab 4 All
Lab 4 All
Here, are the key reasons to perform unit testing in software engineering:
Unit
Testing Levels
1. Unit tests help to fix bugs early in the development cycle and save costs.
2. It helps the developers to understand the testing code base and enables
them to make changes quickly
3. Good unit tests serve as project documentation
4. Unit tests help with code re-use. Migrate both your code and your tests to
your new project. Tweak the code until the tests run again.
Manual
Automated
Unit testing is commonly automated but may still be performed manually. Software Engineering
does not favor one over the other but automation is preferred. A manual approach to unit testing
may employ a step-by-step instructional document.
A developer writes a section of code in the application just to test the function. They
would later comment out and finally remove the test code when the application is
deployed.
A developer could also isolate the function to test it more rigorously. This is a more
thorough unit testing practice that involves copy and paste of code to its own testing
environment than its natural environment. Isolating the code helps in revealing
unnecessary dependencies between the code being tested and other units or data
spaces in the product. These dependencies can then be eliminated.
A coder generally uses a UnitTest Framework to develop automated test cases. Using an
automation framework, the developer codes criteria into the test to verify the correctness
of the code. During execution of the test cases, the framework logs failing test cases.
Many frameworks will also automatically flag and report, in summary, these failed test
cases. Depending on the severity of a failure, the framework may halt subsequent testing.
The workflow of Unit Testing is 1) Create Test Cases 2) Review/Rework 3) Baseline 4)
Execute Test Cases.
Statement Coverage
Decision Coverage
Branch Coverage
Condition Coverage
Finite State Machine Coverage
For example, you might have a function that needs variables or objects that are not
created yet. In unit testing, those will be accounted for in the form of mock objects
created solely for the purpose of the unit testing done on that section of code.
1. Junit: Junit is a free to use testing tool used for Java programming language.
It provides assertions to identify test method. This tool test data first and
then inserted in the piece of code.
2. NUnit: NUnit is widely used unit-testing framework use for all .net
languages. It is an open source tool which allows writing scripts manually. It
supports data-driven tests which can run in parallel.
3. JMockit: JMockit is open source Unit testing tool. It is a code coverage tool
with line and path metrics. It allows mocking API with recording and
verification syntax. This tool offers Line coverage, Path Coverage, and Data
Coverage.
4. EMMA: EMMA is an open-source toolkit for analyzing and reporting code
written in Java language. Emma support coverage types like method, line,
basic block. It is Java-based so it is without external library dependencies
and can access the source code.
5. PHPUnit: PHPUnit is a unit testing tool for PHP programmer. It takes small
portions of code which is called units and test each of them separately. The
tool also allows developers to use pre-define assertion methods to assert
that a system behave in a certain manner.
Those are just a few of the available unit testing tools. There are lots more,
especially for C languages and Java, but you are sure to find a unit testing tool for
your programming needs regardless of the language you use.
Myths by their very nature are false assumptions. These assumptions lead to a
vicious cycle as follows –
Truth is Unit testing increase the speed of development.
Programmers think that Integration Testing will catch all errors and do not execute
the unit test. Once units are integrated, very simple errors which could have very
easily found and fixed in unit tested take a very long time to be traced and fixed.
It’s recommended unit testing be used in conjunction with other testing activities.
Summary
UNIT TESTING is defined as a type of software testing where individual units
or components of a software are tested.
As you can see, there can be a lot involved in unit testing. It can be complex
or rather simple depending on the application being tested and the testing
strategies, tools and philosophies used. Unit testing is always necessary on
some level. That is a certainty.
Lesson 1: How to Download and Install JUnit in
Eclipse
PART 1) Install Java
JUnit is a Testing framework used to test Java based application. So before
installing JUnit, you need to configure or verify java development kit (JDK) in your
machine.
Step 4) Visit https://github.com/junit-team/junit4/wiki/Download-and-
Install again. Click hamcrest-core.jar
Step 5) Download the Jar
For JUnit installation, you need JUnit jars, and you can download the desired
version of JUnit jar file from JUnit official youbsite http://www.junit.org
JUnit.jar
hamcrest-core.jar
For example, if you have created a JUnit folder in c: drive and placed jars there,
then for environment settings you need to open control panel ->advanced -
>environment variable.
When you click on OK, it will create a new system variable with the given name and
value. Which you can verify in environment variable window as shown in step 1
image.
Step 3) After creating JUNIT_HOME, create another variable with the name
CLASSPATH. Again go to Environment Variables and follow the below steps.
1. Click on “new” button. When you click on new in environment variables, it
will open another window.
Step 4) In this step, point out JUNIT_HOME to JUnit.jar which is placed in JUnit
folder as given below:
Step 5) Once you click on the ‘OK’ button, you can verify that a new environment
variable named “CLASSPATH” can be seen under system variable. See below
PART 4) Install JUnit jar file in eclipse
Step 1) Right click on project:
After adding a JUnit.jar file, click on ‘OK’ button to close java build path window.
Part 5) Verifying whether required jar file for JUnit is
in my build path
In order to verify JUnit jar file in eclipse, you need to follow below-mentioned
steps:
In that window, go to Libraries tab to see all jar files. In jar file tree view, you need
to look for the jar file name which is starting with JUnit.
Once you expand JUnit libraries, you can see java libraries as shown below:
Now you are ready to use JUnit with eclipse.
Step 1) Create a java class named TestJUnit.java and provide a simple assert
statement.
package guru99.junit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
@Test
public void testSetup() {
String str= "I am done with Junit setup";
assertEquals("I am done with Junit setup",str);
}
}
Step 2) Create a Test Runner class to execute above test.
package guru99.junit;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
JUnit framework also allows quick and easy generation of test cases and test data.
The org.Junit package consist of many interfaces and classes for JUnit Testing
such as Test, Assert, After, Before, etc.
Setup
@Before annotation in JUnit is used on a method containing Java code to run
before each test case. i.e it runs before each test execution.
Note:
1. createOutputFile()
2. testFile1()
3. deleteOutputFile()
4. createOutputFile()
5. testFile2()
6. deleteOutputFile()
Assumption:
testFile1() runs before testFile2()– which is not guaranteed.
Once-only setup
It is possible to run a method only once for the entire test class before any of
the tests are executed, and prior to any @Before method(s).
“Once only setup” are useful for starting servers, opening communications,
etc. It’s time-consuming to close and re-open resources for each test.
This can be done using the annotation @BeforeClass in JUnit.
MyFirstClassTest.java
package guru99.JUnit;
import org.JUnit.Test;
@Test
public void myFirstMethod(){
String str= "JUnit is working fine";
assertEquals("JUnit is working fine",str);
}
}
TestRunner.java
To execute our test method (above) ,we need to create a test runner. In the test
runner we have to add test class as a parameter in JUnitCore’s runclasses() method
. It will return the test result, based on whether the test is passed or failed.
package guru99.JUnit;
import org.JUnit.runner.JUnitCore;
import org.JUnit.runner.Result;
import org.JUnit.runner.notification.Failure;
Step 1) Consider below java class having various methods which are attached to
above-listed annotations:
JunitAnnotationsExample.java
package guru99.junit;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@BeforeClass
public static void m1() {
System.out.println("Using @BeforeClass , executed before all test cases ");
}
@Before
public void m2() {
list = new ArrayList<String>();
System.out.println("Using @Before annotations ,executed before each test cases ");
}
@AfterClass
public static void m3() {
System.out.println("Using @AfterClass ,executed after all test cases");
}
@After
public void m4() {
list.clear();
System.out.println("Using @After ,executed after each test cases");
}
@Test
public void m5() {
list.add("test");
assertFalse(list.isEmpty());
assertEquals(1, list.size());
}
@Ignore
public void m6() {
System.out.println("Using @Ignore , this execution is ignored");
}
@Test(timeout = 10)
public void m7() {
System.out.println("Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case");
}
@Test(expected = NoSuchMethodException.class)
public void m8() {
System.out.println("Using @Test(expected) ,it will check for specified exception during its execution");
}
}
Step 2) let’s create a test runner class to execute above test:
TestRunner.java
package guru99.junit;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
@Test
public void m5() {
list.add("test");
assertFalse(list.isEmpty());
assertEquals(1, list.size());
}
In above method as you are adding a string in the variable “list” so
As you have added only one string in the list, so the size is one.
list.size() must return int value as “1” .
So assertEquals(1, list.size()) must return true.
As a result, the test case will pass.
@Test(timeout = 10)
public void m7() {
System.out.println("Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case");
}
As discussed above @Test(timeout = 10)annotation is used to enforce timeout in
the test case.
@Test(expected = NoSuchMethodException.class)
public void m8() {
System.out.println("Using @Test(expected) ,it will check for specified exception during its execution");
}
As discussed above @Test(expected) will check for specified exception during its
execution so method m8() will throw “No Such Method Exception.” As a result, the
test will be executed with an exception.
As all test cases are passed, this results in a successful test execution.
Actual Result
As there are three test cases in above example, all test cases will be executed one
by one. See output below:
Using @Test(expected) ,it will check for specified exception during its execution
As you seen earlier, below table describes important Assert methods and
description:
TestResult
2. This method is used to create a TestResult object.
createResult()
3. String getName() This method returns a string which is nothing but a TestCase.
void setName(String
6. This method is used to set a name of a TestCase.
name)
void addFailure(Test test, This method is used if you require add a failure to
2.
AssertionFailedError t) the list of failures.
9. void startTest(Test test) This method is used to notify that a test is started.
void addTestSuite(Class<? extends This method is used if you want to specify the class
2.
TestCase> testClass) while adding a test to the suite.
6. void setName(String name) This method is used to set the name of TestSuite.
Summary:
JUnit provides a portable API, which provides all important classes and
Selenium annotations useful in writing a unit test.
Classes which are very useful while writing a test case
org.junit.Assert
org.junit.TestCase
org.junit.TestResult
org.junit.TestSuite
Important and frequently used JUnit annotations list
@Before
@BeforeClass
@After
@AfterClass
@Test
@Ignore
Lesson 4: Junit Assert & AssertEquals with
Example
What is Junit Assert?
Assert is a method useful in determining Pass or Fail status of a test case, The
assert methods are provided by the class org.junit.Assert which extends
java.lang.Object class.
There are various types of assertions like Boolean, Null, Identical etc.
Junit provides a class named Assert, which provides a bunch of assertion methods
useful in writing test cases and to detect test failure
1. assertTrue(condition)
2. assertFalse(condition)
Null object
If you want to check the initial value of an object/variable, you have the following
methods:
1. assertNull(object)
2. assertNotNull(object)
Identical
If you want to check whether the objects are identical (i.e. comparing two
references to the same java object), or different.
1. assertSame(expected, actual), It will return true if expected == actual
2. assertNotSame(expected, actual)
Assert Equals
If you want to test equality of two objects, you have the following methods
assertEquals(expected, actual)
assertArrayEquals(expected, actual)
Above method must be used if arrays have the same length, for each valid value
for i, you can check it as given below:
assertEquals(expected[i],actual[i])
assertArrayEquals(expected[i],actual[i])
Fail Message
If you want to throw any assertion error, you have fail() that always results in a fail
verdict.
Fail(message);
JUnit assertEquals
You have assertEquals(a,b) which relies on the equals() method of the Object
class.
For Example: Consider below-mentioned strings having same values, let’s test it
using assertTrue
String obj1="Junit";
String obj2="Junit";
assertEquals(obj1,obj2);
Above assert statement will return true as obj1.equals(obj2) returns true.
For example:
You will create few variables and important assert statements in JUnit.
In this example, you will execute our test class using TestRunner.java
Step 1) Lets create a class covering all important assert statement methods in
junit:
Junit4AssertionTest.java
package guru99.junit;
import static org.junit.Assert.*;
import org.junit.Test;
@Test
public void testAssert(){
//Variable declaration
String string1="Junit";
String string2="Junit";
String string3="test";
String string4="test";
String string5=null;
int variable1=1;
int variable2=2;
int[] airethematicArrary1 = { 1, 2, 3 };
int[] airethematicArrary2 = { 1, 2, 3 };
//Assert statements
assertEquals(string1,string2);
assertSame(string3, string4);
assertNotSame(string1, string3);
assertNotNull(string1);
assertNull(string5);
assertTrue(variable1<variable2);
assertArrayEquals(airethematicArrary1, airethematicArrary2);
}
}
Step 2) You need to create a test runner class to execute above class:
TestRunner.java
package guru99.junit;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
1. assertEquals(string1,string2);
Now compare string1=” Junit” with string2=” Junit” with equals method of object
class. Replacing assertEquals method from java.lang.Object.equals() method :
string1.equals(string2)=> returns true
2. assertSame(string3, string4);
“assertSame()” functionality is to check that the two objects refer to the same
object.
Since string3=”test” and string4=”test” means both string3 and string4 are of the
same type so assertSame(string3, string4) will return true.
3. assertNotSame(string1, string3);
“assertNotSame()” functionality is to check that the two objects do not refer to the
same object.
Since string1=”Junit” and string3=”test” means both string1 and string3 are of
different types, so assertNotSame(string1, string3) will return true.
4. assertNotNull(string1);
5. assertNull(string5);
6. assertTrue(variable1<variable2);
7. assertArrayEquals(airethematicArrary1, airethematicArrary2);
Summary:
In this tutorial, you learned all important types of assertion methods provided by
JUnit. Also, you have seen the examples of assert statements. Which shows that if
all assert statements return true, then the test GUI will return a true result and if
the single test fails it will return a failed result.
To run the suite test, you need to annotate a class using below-mentioned
annotations:
1. @Runwith(Suite.class)
2. @SuiteClasses(test1.class,test2.class……) or
Step 2) Create another test class to add (e.g. MySecondClassTest) and create a
method annotated with @test.
Step 3) To create a testSuite you need to first annotate the class with
@RunWith(Suite.class) and @SuiteClasses(class1.class2…..).
Step 4) Create a Test Runner class to run our test suite as given below;
Code Explanation:
Code Line 8: Declaring the main method of the class test which will run our
JUnit test.
Code Line 9: Executing test cases using JunitCore.runclasses which takes
the test class name as a parameter (In the example above, you are using
TestSuiteExample.class shown in step 3).
Code Line 11: Processing the result using for loop and printing out failed
result.
Code Line 13: Printing out the successful result.
Output: Here is the output which shows successful test with no failure trace as
given below:
JUnit Test Suite Example
Consider a more complex example
JunitTest.java
package guru99.junit;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SuiteTest1.class,
SuiteTest2.class,
})
SuiteTest1.java is a test class having a test method to print out a message as given
below. You will use this class as a suite in above mentioned class.
package guru99.junit;
import org.junit.Test;
@Test(expected = ArithmeticException.class)
public void testJUnitMessage() {
@Test
public void testJUnitHiMessage() {
message = "Hi!" + message;
System.out.println("Junit Hi Message is printing ");
assertEquals(message, junitMessage.printHiMessage());
System.out.println("Suite Test 2 is successful " + message);
}
}
SuiteTest2.java
package guru99.junit;
import org.junit.Assert;
import org.junit.Test;
@Test
public void createAndSetName() {
Assert.assertEquals(expected, actual);
System.out.println("Suite Test 1 is successful " + actual);
}
}
Output
1. If you want to ignore a test method, use @Ignore along with @Test
annotation.
2. If you want to ignore all the tests of class, use @Ignore annotation at the
class level.
You can provide the reason for disabling a test in the optional parameter provided
by @Ignore annotation.
It will help other developers working on the same piece of code, to understand
“why a particular test is disabled?” When the issue of that particular test is fixed,
you can simply enable it by removing @Ignore annotation.
JUnitMessage.java
package guru99.junit;
return message;
}
message="Hi!"+ message;
System.out.println(message);
return message;
}
}
JunitTestExample.java
package guru99.junit;
import org.junit.Test;
@Test
public void testJUnitMessage() {
@Test
public void testJUnitHiMessage() {
message="Hi!" +message;
System.out.println("Junit Hi Message is printing ");
assertEquals(message, junitMessage.printHiMessage());
}
}
TestRunner.java
Let’s create a test runner class to execute JunitTestExample.java
package guru99.junit;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Hi!Guru99
Guru99
JunitTestExample.java
package guru99.junit;
import org.junit.Ignore;
import org.junit.Test;
public class JunitTestExample {
@Ignore
@Test
public void testJUnitMessage() {
@Test
public void testJUnitHiMessage() {
message="Hi!" +message;
System.out.println("Junit Hi Message is printing ");
assertEquals(message, junitMessage.printHiMessage());
}
}
Output:
Below output shows that one test is skipped (disabled), see as marked below:
Hi!Guru99
JunitTestExample.java
package guru99.junit;
import org.junit.Ignore;
import org.junit.Test;
@Test
public void testJUnitHiMessage() {
message="Hi!" +message;
System.out.println("Junit Hi Message is printing ");
assertEquals(message, junitMessage.printHiMessage());
}
}
Output:
Same as above.
Let’s modify above example to understand how to ignore all the tests:
package guru99.junit;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class JunitTestExample {
@Test
public void testJUnitMessage() {
System.out.println("Junit Message is printing ");
assertEquals(message, junitMessage.printMessage());
@Test
public void testJUnitHiMessage() {
message="Hi!" +message;
System.out.println("Junit Hi Message is printing ");
assertEquals(message, junitMessage.printHiMessage());
}
}
Output :
As both the tests skipped by using @Ignore at class level so no statement would be
printed on the console.
Summary:
In this tutorial, you learned how to ignore a single test, group of test or all tests by
using @Ignore annotation.
1. If you want to ignore a test method, use @Ignore along with @Test
annotation.
2. If you want to ignore all the tests of class, use @Ignore annotation at the
class level.
You also learned how to provide a statement to make understand other developer,
why a particular test is disabled.
While Testing exception, you need to ensure that exception class you are providing
in that optional parameter of @test annotation is the same. This is because you
are expecting an exception from the method you are Unit Testing, otherwise our
JUnit test would fail.
Example@Test(expected=IllegalArgumentException.class)
By using “expected” parameter, you can specify the exception name our test may
throw. In above example, you are using “IllegalArgumentException” which will be
thrown by the test if a developer uses an argument which is not permitted.
System.out.println(message);
int divide=1/0;
message="Hi!" + message;
System.out.println(message);
return message;
}
}
Code Explanation:
Code Line 7: Creating a parameterized constructor with field initialization.
Code Line 11-14: Creating a method for mathematical operation.
Code Line 18: Creating another method to print a message.
Code Line 20: Creating a new string to print a message.
Code Line 21: Printing new message created in line 20.
Let’s create a test class for above java class to verify exception.
See below test class to unit test exception (ArithmeticException here) throwing
from above java class:
AirthematicTest.java
package guru99.junit;
import org.junit.Test;
@Test(expected = ArithmeticException.class)
public void testJUnitMessage(){
System.out.println("Junit Message is printing ");
junitMessage.printMessage();
@Test
public void testJUnitHiMessage(){
message="Hi!" + message;
System.out.println("Junit Message is printing ");
assertEquals(message, junitMessage.printMessage());
}
}
Code Explanation:
Code Line 13: Using @Test annotation to create our test. As you execute
above classes method, it will invoke a mathematical operation. Here
Arithmetic Exception is expected, so you are listing it out as a parameter in
@Test.
Code Line 17: Invoking printMessage() JUnitMessage.java
Code Line 18: Creating another method to print HI message.
If you execute this test class, the test method is executed with each defined
parameter. In the above example, the test method is executed five times.
Let’s execute it and verify the result. See below the test runner class to
execute JunitTestExample.java
Output:
Here is the output which shows successful test with no failure trace as given below:
Summary:
Exception testing is a special feature introduced in JUnit4. In this tutorial,
you have learned how to test exception in JUnit using @test(excepted)
Junit provides the facility to trace the exception and also to check whether
the code is throwing exception or not
For exception testing, you can use
Optional parameter (expected) of @test annotation and
To trace the information ,”fail()” can be used
But JUnit has a slightly different approach. With JUnit error collector, you can still
continue with the test execution even after an issue is found or test fails. Error
collector collects all error objects and reports it only once after the test execution is
over.
The benefit of adding all errors in an Error Collector is that you can verify all the
errors at once. Also, if the script fails in the middle, it can still continue executing it
Note: In the case of using simple assert or try/catch block , using error collector
method won’t be possible.
Sample code
package guru99.junit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
@Test
public void example() {
collector.addError(new Throwable("There is an error in first line"));
collector.addError(new Throwable("There is an error in second line"));
collector.checkThat(getResults(),
not(containsString("here is an error")));
// all lines of code will execute and at the end a combined failure will
be logged in.
}
}
There are several built-in rules provided by JUnit API that a tester can use, or even
you can write our own rule.
See below line of code, which shows how to use @rule annotation along with Error
Collector:
@Rule
public ErrorCollector collector= new ErrorCollector();
See below code which simply creates a rule which is nothing but creating “Error
Collector object.” Which is further used to add all the errors in order to report the
issue at the end:
ErrorCollectorExample.java
package guru99.junit;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
@Test
public void example() {
collector.addError(new Throwable("There is an error in first line"));
collector.addError(new Throwable("There is an error in second line"));
System.out.println("Hello");
try {
Assert.assertTrue("A " == "B");
} catch (Throwable t) {
collector.addError(t);
}
System.out.println("World!!!!");
}
}
TestRunner.java
Let’s add above test class in a test runner and execute it to collect all errors. See
below code:
package guru99.junit;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
See the failure trace which traces all the errors in one place:
Benefits of JUnit ErrorCollector
You can use JUnit assertion for functional or GUI validation e.g.
Using assertion, validation test becomes easy. But one major issue is that test
execution will stop even if a single assertion fails.
Test continuity and recovery handling is crucial to test automation success. Error
Collector is the best way to handle such kind of scenarios.
Summary:
Junit error collector allows a test to continue even after the first issue is
found and test fails at the end
Error collector collects all error objects and reports it only, after all, the test
execution over
The benefit of adding all errors in an Error Collector is that you can verify all
the errors at once
Error collector simply adds errors using method addError(throwable err)
provided by ErrorCollector.java.
Using Parameterized test, one can set up a test method that retrieves data from
some data source.
Consider a simple test to sum different numbers. The code may look like –
We need a simple approach and. Using parameterized test you can just add a
method to input 10 data inputs and your test will run 10 times automatically.
Code Explanation
This class is responsible for tests to run with a new test instance. It is responsible
for invoking JUnit lifecycle methods such as setup(associate resources) and
teardown(release resources).
To parameterize you need to annotate using @RunWith and pass required .class to
be tested
Step 3) Create a constructor that stores the test data. It stores 3 variables
Step 4) Create a static method that generates and returns test data.
{1,2,3}
Here
firstNumber =1
secondNumber=2
expectedResult=3
Here each array element will be passed to the constructor, one at a time as the
class is instantiated multiple times.
Code Line 8: Declaring the main method of the class test which will run our
JUnit test.
Code Line 9: Executing test cases using JunitCore.runclasses, it will take the
test class name as a parameter (In our example we are using
Airthematic.class).
Code Line 11: Processing the result using for loop and printing out failed
result.
Code Line 13: Printing out the successful result.
Output:
Here is the output which shows successful test with no failure trace as given below:
See the result on console,which shows addition of two numbers :-
Summary:
Parameterized test enables developer to execute the same test over and over again
using different values.
@RunWith
@Parameters
Lesson 10: TestNG Vs JUnit: What’s the
Difference?
Both Testng and Junit are Testing framework used for Unit Testing. TestNG is
similar to JUnit. Few more functionalities are added to it that makes TestNG more
powerful than JUnit.
This tutorial is mainly focused to analyse features of JUnit and TestNG. It help
developers to decide which framework should be used for Unit Testing. Let’s
analyse similarities between TestNG and JUnit4 first.
Here is the table that shows the features supported by JUnit and TestNG.
Annotations
Both JUnit and TestNG uses annotations and almost all the annotations looks
similar.
Both TestNG and Junit4 uses @Test(timeout = 1000) for timeout .Check the table
below for more details-
S.N. Description TestNG JUnit 4
@Test(expectedExceptions = @Test(expected =
7 annotation for exception
ArithmeticException.class) ArithmeticException.class)
Suite Test
Suites are used to execute multiple tests together. Suites can be created using both
TestNG and JUnit4. However, suites are more powerful in TestNG as it uses very
different method for execution of tests. Let’s understand it using code snippet as
given below:
Using JUnit4
package guru99.junit;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SuiteTest1.class,
SuiteTest2.class,
})
TestNG uses xml to bundle all tests at one place.Below xml describes use of suite
while working with TestNG:
Ignore Test
Using both we can skip a test .Let’s see it using code example as given below:
Using JUnit4
Below code snippet describes use of @ignore annotation while working with
JUnit4:
@Ignore
public void method1()
{
System.out.println("Using @Ignore , this execution is ignored");
}
Using TestNG
@Test(enabled=false)
public void TestWithException()
{
System.out.println("Method should be ignored as it's not ready yet");
}
Exception Test
Exception testing is available both in TestNG and JUnit4. It is used to check, which
exception is thrown from the test?
Using JUnit4
Below code snippet describes use of exception test while working with JUnit4:
@Test(expected = ArithmeticException.class)
public void divideByZero()
{
Int i = 1/0;
}
Using TestNG
Below code snippet describes use of exception test while working with TestNG:
@Test(expectedExceptions = ArithmeticException.class)
public void divideByZero()
{
Int i = 1/0;
}
Timeout
This feature is implemented both in TestNg and JUnit4.Timeout is used to
terminate a test which takes longer than specified time (in milliseconds).
Using JUnit4
Below code snippet describes use of timeout test while working with JUnit4:
@Test(timeout = 1000)
public void method1()
{
while (true);
}
Using TestNG
Below code snippet describes use of timeout test while working with TestNG:
@Test(timeOut = 1000)
public void method1()
{
while (true);
}
Parameterized Test
JUnit provides an easier and readable approach to test known as Parameterized
test. Both TestNG and JUnit supports parameterized test but differ in the way they
define the parameter value. Let see this one by one.
Using JUnit4
@RunWith(value = Parameterized.class)
public class JunitTest{
privateint number;
@Parameters
public static Collection<Object[]> data()
{
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
returnArrays.asList(data);
}
@Test
public void parameterTest()
{
System.out.println("Parameterized Number is : " + number);
}
}
Using TestNG
}
See below xml file to be used for above class:
<classes>
<class name="com.guru99.Test1" />
</classes>
</test>
</suite>
Summary :
We saw JUnit4 and TestNG comparison in details. We also saw both are similar
except parameterized test and dependency test. In short we can say, based on
flexibility and requirement we can choose any one of them for Unit Testing.