JUNIT—An Introduction
Ø It is an open source Unit testing framework.
Ø It provides a simple way to explicitly test specific areas of a Java program
Ø It helps us in writing and running automated tests.
Why do you need Junits
Ø They are simple.
Ø They check results of their own and provide immediate results.
Ø It’s inexpensive.
Ø It increases the stability of software which is being tested.
Design of a Junit
Ø The design of a junit is simple and it can be done in two ways :
- Command pattern
- Composite Pattern
How to install a Junit in your PC
Ø Installing a Junit is not a complex task.
Ø The following are the steps involved while installing a junit in you PC:
§ Down Load it from web
§ Unzip the junit.zip distribution file to a directory
§ Add JUnit to the classpath
Set CLASSPATH=%Directory-name%\junit.jar
§ Test the installation by using either the textual or graphical test runner to run the sample tests which is present in the directory.
Writing a test Case Using Junit
Ø Define a subclass of TestCase.
Ø Override the setUp() and tearDown() (optional)method.
Ø Define one or more public test () methods of the object(s) under test and assert expected results.
How to write a Test Suite
Ø A test suite is nothing but adding up of several test cases which help us to run all test cases in one go.
Ø The Steps involved in writing a Suite are :
§ Write a Java class that defines a static suite () factory method that creates a TestSuite containing all the tests.
§ Define a main () method that runs the TestSuite in batch mode(which can be optional).
How to Run Junit
Ø Junit provides a graphical as well as textual interface for testing. User can choose from either of them for testing.
For graphical we have to import
java junit.swingui.TestRunner
For Textual we have to import
Java junit.textui.TestRunner
Trends
Ø Junit 4.4 Version is being released.
Ø Junit Can be downloaded from SourceForge.
Ø Junits is used in other languages like C#,FORTRAN,PERL
Example of a JUNIT
A Sample Class to test with Junit
public class Hello
{
Public String getHelloWorld () { return “Hello World";
}
Test Case For helloworld
public class testHello extends TestCase
{
protected Hello hello;
protected void setUp()
{
hello = newHello ();
}
public void testGetHelloWorld()
{
System.out.println ("HelloWorld example");
String result = "Hello World";
//Assert statement is given to check whether the given result is equal to the returnvalueof function
Assert.assertEquals (result, Hello.getHelloWorld ());
}
//Main method is used for run tests for this class only
public static void main(String[] args)
{
junit.swingui.TestRunner.run (testHello.class);
}
}
}
Unit Testing is a test development process by which individual module of the class will be tested. Junit is a simple test framework for writing unit test cases for java programs. Junit is very helpful in test driven development (TDD); it provides functionalities to the developer for writing and running unit test cases for a project in development.
Test Coverage: Test coverage helps in measuring the amount of code covered under testing.
Test Coverage: Test coverage helps in measuring the amount of code covered under testing.
Test Coverage criteria’s:
1. Statement coverage
2. Branch coverage
3. Case coverage
4. Path Coverage.
Junit plays a vital role in improving the test coverage for projects.
Junit 4.x is a completely different API from its earlier versions of Junit. It is based on new features added to java 5.0 and uses annotation for indentifying the test cases. Junit 4.x is simple and easier API for writing test cases and provides flexible ways to the user to introduce flexible initialization, test cleanups, timeout messages, and creating parameterized test cases.
Test class with Junit 4.x:
1. Annotate a test method with @Test (Used by the framework for identifying the test case).
2. Use any suitable asserts method provided by framework to test expected and actual results.
Some of the important features Added in Junit 4.x:
1. Annotations:
Junit 4.x simplifies the testing by exploiting the java 5.0’s new feature called annotations. Annotations feature really helpful in identifying the test cases instead of relying on sub classing, reflection and naming features.
Available annotation in Junit 4.x:
Annotation. | Description. |
@Test | Used to identify the test method. |
@Before | Executes the method annotated with “@Before” before executing the test method. Ex: Test method setup, providing input data. |
@After | Executes the method annotated with “@After” after executing the test method. Ex: Test data clean up operations. |
@BeforeClass | Executes the method before start executing all test methods present in test class. Ex: Providing DB connections. |
@AfterClass | Executes the method after executing all test methods present in test class. Ex: removing DB connections. |
@ignore | Test method annotated with @ignore will be ignored by the framework. |
@Test(timeout=200) | Fails the test case if execution time exceeds more than 200 ms. |
@Test(expected=IllegalArgument Exception.class) | Tests the method only if it throws mentioned exception. |
2. Assert Statements:
Assert statements helps in testing the excepted results against the actual results.
Some of the available Assert methods in Junit 4.x:
Note: AssertArrayEquals() methods are available for all basic types in java.
3. Parameterized Test Cases:
This will allows us to run the same test case with different data. The prerequisite for parameterized test cases is to have an annotation @RunWith for the test class.
@RunWith (value = Parameterized.class)
4.Test Suits:
In Junit 3.* we need to add a suit() method for test classes to run all test cases as a test suit. But in Junit 4.x we can achieve this by using annotations. We use @RunWith and @Suite annotations.
package com.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({TestSampleCalculator.class})
publicclass RunAllTests {
}
Installation:
2. To make Junit jar available to the project we have to add it to the java build path (Eclipse – using add libraries).
Sample Example: SampleCalculator.java
package com.code;
publicclass SampleCalculator {
publicint add(int a, int b){
int result = a + b;
return result;
}
publicint sub(int a, int b){
int result = a - b;
return result;
}
publicint div(int a, int b){
int result = a / b;
return result;
}
publicint mul(int a, int b){
int result = a * b;
return result;
}
}
Junit Test case for the above java class:
package com.test;
importstatic org.junit.Assert.*;
import com.code.SampleCalculator;
import org.junit.Ignore;
import org.junit.Test;
publicclass TestSampleCalculator {
@Test
publicvoid add(){
int[] actuals = {new SampleCalculator().add(1, 1), newSampleCalculator().add(2, 2)};
assertArrayEquals(expecteds, actuals);
}
@Test
publicvoid sub(){
int[] actuals = {new SampleCalculator().sub(4, 2), new SampleCalculator().sub(6, 2)};
assertArrayEquals(expecteds, actuals);
}
@Test
publicvoid div(){
int[] actuals = {new SampleCalculator().div(4, 2), new SampleCalculator().div(8, 2)};
assertArrayEquals(expecteds, actuals);
}
@Test
publicvoid mul(){
int[] actuals = {new SampleCalculator().mul(1, 2), new SampleCalculator().mul(2, 2)};
assertArrayEquals(expecteds, actuals);
}
// This test case expects an ArithmeticException. IF the method throws it, then the test case will pass.
@Test(expected= ArithmeticException.class)
publicvoid divCheck(){
assertEquals(2, new SampleCalculator().div(4, 0));
}
// This test case will be ignored by the Framework.
@Ignore
publicvoid nulCheck(){
assertEquals(10, new SampleCalculator().mul(2, 6));
}
publicstaticint[] expecteds = {2,4};
}.
No comments:
Post a Comment
I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.