2. What is JUnit?
• JUnit is an open source regression testing framework.
• Written by Erich Gamma and Kent Beck
• Part of xUnit family. (e.g. NUnit, CPPUnit etc)
• Eclipse includes JUnit. You can also run JUnit outside of
Eclipse using JUnit’s window.
• Home page:
– http://junit.org.
3. Unit Testing
• Key element in Extreme Programming.
• Focuses on fundamental block at a time.
• Helps to find problems early.
• Easy to maintain.
• Simplifies Integration testing.
4. Unit Testing (contn..)
• Proves as documentation of System(proves that
system works).
• Leads to high quality code, higher productivity and
low maintenance.
• JUnit helps developer write unit tests as they
develop the system.
• Makes writing test cases easy and painless.
6. Principles of testing frameworks.
• Each unit test should run independently of all other
unit tests.
• Errors must be detected and reported test by test.
• It must be easy to define which unit tests will run.
• It should be easy to add unit tests.
• Help us reduce the cost of writing tests by reusing
code.
7. Terminologies in Junit
•A test case tests single method.
Runner Result
Test Suite •A unit test tests all methods in a class.
Unit Test 3 •A test suite combines unit test cases.
• Test fixtures provide software support for all
Unit Test 2 operations. (e.g. mock database)
•The test runner runs the unit test or entire test
suite.
Unit Test 1
•The test result collects & summarizes all test
information of tests e.g. a test can pass , fail
Test Fixtures (assertion error) and error (exception is thrown)
8. Important Classes and Annotation of
Junit Framework
Test : - Annotation that tells that the attached method is a test method.
Suite :- A class which runs all the unit test cases defined in @SuiteClasses
annotation.
Assert:- Assert class provides lot of assert methods which we can use to throw an
exception if the proposition to it fails.
Runner:- It runs a unit test/ suite and notifies RunNotifier of the significant
event.
RunListener :- Listens to events triggered by Runner. (e.g. Test Begin, Test End etc)
Result:- Collects and summarizes all the information from multiple tests.
11. Simple Case Study
• Create a Java project in Eclipse with two folders
– src : will hold all the source code files
– test: will hold all the test cases
• Write a method ‘multiply’ in Java class.
/** This method multiplies the two integers.
* @param x : first integer to be multiplied.
* @param y : second integer to be multiplied.
* @return integer product
*/
public int multiply(int x, int y)
{
return x/y;
}
12. Simple Case Study (cond..)
• Create a JUnit test case in ‘test’ folder . (File->
New - > JUnit Test Case)
• Add method to test the ‘multiply’ method.
@Test
/**
* test method to test Multiply functionality.
*/
public void testMultiply() {
MyFirstClass tester = new MyFirstClass();
assertEquals("Result", 50, tester.multiply(5, 10));
}
13. Simple Case Study (cond..)
• To execute the test case just right click and say Run as Junit
test.
The bar will be red if
the test fails.
It also displays in
Failure trace the
expected value and
actual output of
function in test.
14. Example 2
public class TestCounter {
//Declare Counter
Counter objCounter; Test class for Counter.
@Before Note*:
public void setUp()
Each test begins with a brand new
{
objCounter = new Counter(); Counter object. So for the
} decrement method we compared
return value with -1.
@Test
public void testIncrement() { Each tests are independent of each
assertTrue(objCounter.increment() == 1); other.
assertTrue(objCounter.increment() == 2);
}
@Test
public void testDecrement() {
assertTrue(objCounter.decrement() == -1);
}
}
15. public class Counter {
Example 2
This is actual Counter Class.
int intCounter = 0;
//increament's counter
public int increment(){
return intCounter+=1;
}
//decreament's counter
public int decrement(){
return intCounter-=1;
}
//return's counter
public int getIntCounter()
{
return intCounter;
}
}
16. Expected Exception handling TestCases
Method to test: Test Case
public class ArrayManipulations { int[] a1= {1,2,3,4,5,6,7,8,9,10}; //length=10
int[] b1= {0,2,4,6,8,10}; //length 6
public void Bar(int a[],int b[], int n) @Test(expected =
{ ArrayIndexOutOfBoundsException.class)
a[0]=b[0]; public void testBarPreconditions() {
int i=1; ArrayManipulations tester = new
while (i<n) { ArrayManipulations();
a[i]=b[i]+a[i-1];
a[i-1]=0; int n = 11;
i=i+1; tester.Bar(a1, b1, n);
} }
}
}
17. Test Suites
• Test Suite is created from
import org.junit.runner.RunWith; New->Others->Junit->Junit Test
import org.junit.runners.Suite; Suite
import org.junit.runners.Suite.SuiteClasses;
•The suite will run all tests in
classes mentioned in
@RunWith(Suite.class) @SuiteClasses
@SuiteClasses({ MyTestClass.class, TestCounter.class })
public class AllTests { •We can add on the .class
names whenever a new unit
} test is created.
18. Advantages of Junit framework
• Alternate front ends to display results of tests are available
like command line, AWT and Swing.
• Separate class loaders for each unit test to avoid side
effects.
• Provides methods like setUp and tearDown for standard
resource initialization.
• A set of assert methods to check results of tests.
• Integration with popular tools such as Ant and Maven and
IDE’s like Eclipse and Jbuilder.
19. Disadvantages of Junit Framework
• Cannot do dependency testing. TestNG allows this.
• Not suitable for higher level testing. (Large test suites.)
1. It is designed for the purpose of writing and running tests in Java language.2. JUnit was originally written by Erich Gamma and Kent Beck3. Can be run through external interfaces like graphical swing test runner.
We have learned in our lecture that Unit testing is a key element in the Extreme programming.It focuses on testing one fundamental block at a time rather than module level functional testing. This make code easy to maintainSimplifies Integration testing.
It proves as a documentation of System.It improves the code quality, increases productivity and reduces the maintenance.The direct way to test some functionality in java is we write a method which passes some arguments to the method to be tested and then we print out the return value. But it is pain to write so many lines every time we want to test a method. Also when the output is printed multiple times on the screen it is hard to look at so many lines and identify whether a method runs correctly or not.Junit makes testing very easy and painless as we will see in next few slides.It also helps developer to write the unit tests in parallel with the development of a system.http://en.wikipedia.org/wiki/Unit_testing#Benefitshttp://googletesting.blogspot.com/2009/07/by-shyam-seshadri-nowadays-when-i-talk.html
Junit is pretty widely used in Application which are build using Test Driven Development Approach.TDD = : first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test and finally refactors the new code to acceptable standards
These features are required in testing frameworks. Junit provides all these features.
Test: This is an annotation which tells that the attached method is to test a unit program.Suite: Runs collection of TestCases from different Test Classes.Assert: This is a silent method. It throws an exception when if the proposition fails.Runner: It runs a test and notifies RunNotifier of the significant events.RunListener: Responds to any events triggered during test in progress. E.g. Test Begins, Test Ends, any failure or error.Result:It collects and summarizes all the information from running multiple tests. A test can Pass, Fail(Assertion Error) or has Error when an exception is thrown.
@BeforeClass public static void init() { // Do one-time setup for all test cases } // init() @Before public void doSetup() { // Do setup before each test case } // setUp() @After public void doTearDown() { // Do tear down after each test case } // tearDown() @AfterClass public static void destroy() { // Do tear-down after all test cases are finished } // destroy() @Test public void testFactorial() {//Test methods.}
All these methods are static methods.
Eclipse comes with Junit
@Test attribute denotes the test case.
Junit view.
We saw on previous slides that setUp method is called before each test method. So a brand new counter is assigned to each method.
Interceptor-in 4.7 allows to expect multiple exceptions.
Consider an example where I need to have Login details before any of the any access is made to database. TestNG:= is also a popular and well-known tool for testing Java. Next generation Java Testing.TestNG is especially useful with large test suites, where one test's failure shouldn't mean having to rerun a suite of thousands