JUnit Tutorial
JUnit Tutorial
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test- driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated with JUnit.
Features
1. JUnit is an open source framework which is used for writing & running tests.
2. Provides Annotation to identify the test methods.
3. Provides Assertions for testing expected results.
4. Provides Test runners for running tests.
5. JUnit tests allow you to write code faster which increasing quality
6. JUnit is elegantly simple. It is less complex & takes less time.
7. JUnit tests can be run automatically and they check their own results and provide
8. immediate feedback. There's no need to manually comb through a report of test results
9. JUnit tests can be organized into test suites containing test cases and even other test suites.
10. Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
Sample Test Class
package com.test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class JunitTest {
@Test
public void testJunit() {
String msg = "Junit working";
assertEquals("Junit working", msg);
}
}
|
Features
JUnit test framework provides following important features
1. Fixtures
2. Test suites
3. Test runners
4. JUnit classes
Fixtures
Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a
test fixture is to ensure that there is a well known and fixed environment in which tests are run so
that results are repeatable. It includes
1. setUp() method which runs before every test invocation
2. tearDown() method which runs after every test method.
public class JunitTest extends TestCase {
int val1,val2;
protected void setUp() {
// TODO Auto-generated method stub
val1=10;
val2=12;
}
@Test
public void testJunit() {
int result=val1+val2;
assertTrue(result == 22);
}
}
|
Test suite
Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
Junit classes
JUnit classes are important classes which is used in writing and testing JUnits. Some of the important classes are
1. Assert which contain a set of assert methods.
2. TestCase which contain a test case defines the fixture to run multiple tests.
3. TestResult which contain methods to collect the results of executing a test case.
JUnit API
The most important package in JUnit is junit.framework which contain all the core classes. Some of the important class are
Serial No
|
Class Name
|
Functionality
|
1
|
Assert
|
A set of assert methods.
|
2
|
TestCase
|
A test case defines the fixture to run multiple tests.
|
3
|
TestResult
|
A TestResult collects the results of executing a test case
|
4
|
TestSuite
|
A TestSuite is a Composite of Tests.
|
Assert Class
public class Assert extends java.lang.Object
|
No
|
Method
|
Description
|
1
|
void assertEquals(boolean expected, boolean actual)
|
Check that two primitives/Objects are equal
|
2
|
void assertFalse(boolean condition)
|
Check that a condition is false
|
3
|
void assertTrue(boolean condition)
|
Check that a condition is true
|
4
|
void assertNotNull(Object object)
|
Check that an object isn't null.
|
5
|
void assertNull(Object object)
|
Check that an object is null
|
6
|
void fail()
|
Simply Easy Learning Fails
a test with no message.
|
int val1,val2;
protected void setUp() {
// TODO Auto-generated method stub
val1=10;
val2=12;
}
@Test
public void testJunit() {
int result=val1+val2;
assertTrue(result == 22);
//assertFalse(result==0);
assertEquals(22, result);
assertNotNull(result);
//assertNull(result);
}
|
TestCase Class
public abstract class TestCase extends Assert implements Test
|
No
|
Method
|
Description
|
1
|
int countTestCases()
|
Counts the number of test cases executed by run(TestResult result).
|
2
|
TestResult createResult()
|
Creates a default TestResult object
|
3
|
String getName()
|
Gets the name of a TestCase
|
4
|
TestResult run()
|
A convenience method to run this test, collecting the results with a default TestResult object
|
5
|
void run(TestResult result)
|
Check that an object is null
|
6
|
void setName(String name)
|
Sets the name of a TestCase
|
7
|
void setUp()
|
Sets up the fixture, for example, open a network connection
|
8
|
void tearDown()
|
Tears down the fixture, for example,
close a network connection
|
9
|
String toString()
|
Returns a string representation of the test case
|
TestResult Class
public class TestResult extends Object
|
A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between failures and errors. A failure is anticipated and checked for with assertions.
No
|
Method
|
Description
|
1
|
void addError(Test test, Throwable t)
|
Adds an error to the list of errors.
|
2
|
Void addFailure(Test test, AssertionFailedError t)
|
Adds a failure to the list of failures.
|
3
|
void endTest(Test test)
|
Informs the result that a test was completed.
|
4
|
int errorCount()
|
Gets the number of detected errors
|
5
|
Enumeration<TestFailure> errors()
|
Returns an Enumeration for the errors.
|
6
|
int failureCount()
|
Gets the number of detected failures.
|
7
|
void run(TestCase test)
|
Runs a TestCase.
|
8
|
int runCount()
|
Gets the number of run tests.
|
9
|
void startTest(Test test)
|
Informs the result that a test will be started.
|
10
|
void stop()
|
Marks that the test run should stop.
|
TestSuite Class
public class TestSuite extends Object implements Test
|
A TestSuite is a Composite of Tests. It runs a collection of test cases. Some of the important methods of TestSuite class are
No
|
Method
|
Description
|
1
|
void addTest(Test test)
|
Adds a test to the suite.
|
2
|
void addTestSuite(Class<? extends TestCase> testClass()
|
Adds the tests from the given class to the suite.
|
3
|
int countTestCases()
|
Counts the number of test cases that will be run by this test.
|
4
|
String getName()
|
Returns the name of the suite.
|
5
|
void run(TestResult result)
|
Runs the tests and collects their result in a TestResult.
|
6
|
void setName(String name)
|
Sets the name of the suite.
|
7
|
Test testAt(int index)
|
Returns the test at the given index.
|
8
|
int testCount()
|
Returns the number of tests in this suite.
|
public static void main(String[] a) { // add the test's in the suite
TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class, TestJunit3.class );
TestResult result = new TestResult();
suite.run(result);
System.out.println("Number of test cases = " + result.runCount());
}
|
JUnit Using Assertion
Calculator.java
package com.test;
public class Calculator {
private int no1;
private int no2;
public Calculator(int no1, int no2) {
super();
this.no1 = no1;
this.no2 = no2;
}
/**
* @return the no1
*/
public int getNo1() {
return no1;
}
/**
* @param no1 the no1 to set
*/
public void setNo1(int no1) {
this.no1 = no1;
}
/**
* @return the no2
*/
public int getNo2() {
return no2;
}
/**
* @param no2 the no2 to set
*/
public void setNo2(int no2) {
this.no2 = no2;
}
}
|
Calculation.java
package com.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class Calculation {
public int add(Calculator nos){
return nos.getNo1()+nos.getNo2();
}
public int mul(Calculator nos){
return nos.getNo1()*nos.getNo2();
}
@Test
public void testCal(){
Calculator nos=new Calculator(1,2);
String[] expectedArray = {"one", "two", "three"};
String[] resultArray = {"one", "two", "three"};
//Check that two objects are equal
assertEquals(3,add(nos));
//Check that a condition is true
assertTrue(2==mul(nos));
//Check that a condition is false
assertFalse(2!=mul(nos));
//Check that an object isn't null
assertNotNull(mul(nos));
//Check that an object is null
assertNull(null);
//Check if two object references point to the same object
assertSame(2,mul(nos));
//Check if two object references not point to the same object
assertNotSame(3,mul(nos));
}
}
|
Annotation
Annotations are like meta-tags that you can add to you code and apply them to methods or in class. These annotation in JUnit gives us information about test methods , which methods are going to run before & after test methods, which methods run before & after all the methods, which methods or class will be ignore during execution.
No
|
annotation
|
Description
|
1
|
@Test
|
Adds a test to the suite.
|
2
|
@Before
|
Adds the tests from the given class to the suite.
|
3
|
@After
|
Counts the number of test cases that will be run by this test.
|
4
|
@BeforeClass
|
Returns the name of the suite.
|
5
|
@AfterClass
|
Runs the tests and collects their result in a TestResult.
|
6
|
@Ignore
|
Sets the name of the suite.
|
package com.test;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
// TODO: Auto-generated Javadoc
/**
* The Class JunitAnnotation.
*/
public class JunitAnnotation {
/**
* execute only once, in the starting
*/
@BeforeClass
public static void beforeClass(){
System.out.println("Before class");
}
/**
* execute only once, in the end
*/
@AfterClass
public static void afterClass(){
System.out.println("After class");
}
/**
* execute for each test, before executing test
*/
@Before
public void before(){
System.out.println("before");
}
/**
* execute for each test, after executing test
*/
@After
public void after(){
System.out.println("after");
}
/**
* test case 2
*/
@Test
public void test2(){
System.out.println("test 2");
}
/**
* test case 1
*/
@Test
public void test1(){
System.out.println("test 1");
}
/**
* ignore the test and that test will not be executed
*/
@Ignore
public void ignore(){
System.out.println("Ignore");
}
}
|
Output:
Before class
before
test 1
after
before
test 2
after
After class
|
See the above output and this is how the JUnit execution procedure is.
l First of all beforeClass() method execute only once
l Lastly, the afterClass() method executes only once.
l before() method executes for each test case but before executing the test case.
l after() method executes for each test case but after the execution of test case
l In between before() and after() each test case executes.
JUnit Test Suite
Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and@Suite annotation are used to run the suite test. This tutorial will show you an example having two Calculation & JunitAnnotation test classes to run together using Test Suite
package com.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ Calculation.class,JunitAnnotation.class })
public class JunitTestSuite {
}
|
Note: for this Junit does not allow parameter constructor, else it will display below exception
initializationError(com.test.Calculator): Test class should have exactly one public zero-argument constructor
initializationError(com.test.Calculator): No runnable methods
|
JUnit Time Test
Junit provides a handy option of Timeout. If a test case takes more time than specified number of milliseconds then Junit will automatically mark it as failed. The timeout parameter is used along with @Test annotation. Now let's see @Test(timeout) in action.
/**
* test case 1 with timeout
*/
@Test(timeout=0)
public void test1(){
System.out.println("test 1");
}
|
JUnit Exception Test
Junit provides a option of tracing the Exception handling of code. You can test the code whether code throws desired exception or not. The expected parameter is used along with @Test annotation. Now let's see @Test(expected) in action.
@Test(expected=ArithmeticException.class)
public void testJunit() {
System.out.println(1/0);
}
|
JUnit Parameterized Test
JUnit 4 has introduced a new feature Parameterized tests. Parameterized tests allow developer to run the same test over and over again using different values. There are five steps, that you need to follow to create Parameterized tests.
l Annotate test class with @RunWith(Parameterized.class)
l Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.
l Create a public constructor that takes in what is equivalent to one "row" of test data.
l Create an instance variable for each "column" of test data.
l Create your tests case(s) using the instance variables as the source of the test data.
package com.test;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class JunitTest {
private Integer no1;
private Integer no2;
public JunitTest(Integer no1,Integer no2) {
this.no1 = no1;
this.no2 = no2;
}
@Parameterized.Parameters
public static Collection parameter(){
return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
{ 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
}
@Test
public void testParameter(){
System.out.println("iput no1="+no1+"\t iput no2="+no2);
}
}
|
Comments
Post a Comment