SlideShare a Scribd company logo
JUNIT
BY ANJUM ARA
HISTORY
• Kent Beck developed the first xUnit automated test tool for Smalltalk in mid-90’s
• Beck and Gamma (of design patterns Gang of Four) developed JUnit on a flight from
Zurich to Washington, D.C.
• Martin Fowler: “Never in the field of software development was so much owed by
so many to so few lines of code.”
• Junit has become the standard tool for Test-Driven Development in Java
• Junit test generators now part of many Java IDEs (Eclipse, BlueJ, Jbuilder, DrJava)
• Xunit tools have since been developed for many other languages (Perl, C++, Python,
Visual Basic, C#, …)
UNIT TESTING
• Unit Testing is one of the phase of software development process in which
units(smallest part of the application) are separately examined for proper operation.
• Generally programmers and occasionally white box testers created unit tests.
• Its implementation can vary from being very manual (pencil and paper) to being
formalized as part of build automation.
TESTS THAT ARE PERFORMED DURING THE UNIT
TESTING ARE EXPLAINED BELOW
• Module Interface test: In module interface test, it is checked whether the information is properly
flowing in to the program unit (or module) and properly happen out of it or not.
• Local data structures: These are tested to inquiry if the local data within the module is stored
properly or not.
• Boundary conditions: It is observed that much software often fails at boundary related conditions.
That’s why boundary related conditions are always tested to make safe that the program is properly
working at its boundary condition’s.
• Independent paths: All independent paths are tested to see that they are properly executing their task
and terminating at the end of the program.
• Error handling paths: These are tested to review if errors are handled properly by them or not.
FAMOUS JAVA UNIT TESTING TOOLS
• JMockit
• Artima SuiteRunner
• Cactus
• Checkstyle
• Cobertura
• Continuous Testing
• Daedalos JUnit Extensions
• Dbunit
• DDSteps
• Jete
• Jetif
• JFCUnit
• Jiffie
• jMock
• JOSIT
• JsTester
• JSystem
• DepUnit
• djUnit
• Dumbster
• EasyMock +
ClassExtension
• EclEmma
• Ejb3unit
• Emma
• Feed4JUnit
• Fest
• Findbugs
• Gretel
• GroboUtils
• Hansel 1.0
• Haste
• J2ME Unit
Testing Toolkit
• Jacareto
FAMOUS JAVA UNIT TESTING TOOLS
• JUnitPerf
• JXUnit
• Macker
• Mockito
• MockObjects
• Mockrunner
• MoMEUnit
• moreUnit
• NoUnit
• TestGen4J
• TestNG
• UISpec4J
• Unitils
• XHTMLUnit
• Xtest
• Fest
• Findbugs
• Gretel
• Pisces
• PMD
• Quilt
• Slim
• Sonar
• StrutsTestCase
for JUnit v1.9.5
• T2
• TagUnit
• Testare
• GroboUtils
• Hansel 1.0
• Haste
• J2ME Unit
Testing Toolkit
• Jailer
• JDepend
• JEasyTest
• JellyUnit
• Jester
• JTestCase
• Jumble
• JUnit
• JUnit-addons
• JUnitDoclet
• JUnitEE
JUNIT
• It is part of unit testing frameworks family collectively known as xUnit. Other examples are
CPPUnit, PHPUnit, JSUnit etc.
• JUnit is linked as a JAR at compile-time; the framework resides under packagesjunit.framework for
JUnit 3.8 and earlier and under org.junit for JUnit 4 and later.
• JUnit has now become the standard tool for Test-Driven Development in Java.
• JUnit test generators now part of many Java IDEs (Eclipse, BlueJ, Jbuilder, DrJava etc).
JUNIT (CONTD…)
• JUnit provides Annotation to identify the test methods and utility methods to assert expected results.
• JUnit has Test runners for running tests.
• JUnit tests can be organized into test suites which contains test cases and other test suites.
• JUnit Framework can be easily integrated with either of the followings:
• Eclipse
• Ant
• Maven
TESTING VIA JUNIT
• Can test JUnit by using Test Case & Test Suit .
• Test Case: A Test Case is a java class which is used to test a single class.
• Test Suite :A Test Suit is a java class which contains many test cases or java classes to test together in
a single run.
BENEFITS
• Simple framework for writing automated, self-verifying tests in Java
• Support for test assertions
• Test suite development
• Immediate test reporting
FEATURES
• Annotation to identify the test methods(After JUnit 4 ).
• Assertions for testing expected results.
• Test fixtures for sharing common test data.
• Test runners for running tests.
• Aggregating tests using suites.
NEED OF JUNIT
• JUnit tests allow you to write code faster while increasing quality.
• JUnit is elegantly simple. It is less complex & takes less time.
• JUnit tests can be run automatically and they check their own results and provide immediate feedback.
There's no need to manually comb through a report of test results.
• JUnit tests can be organized into test suites containing test cases and even other test suites.
• Writing JUnit tests is inexpensive.
JUNIT ANNOTATIONS
• @Test : The Test annotation tells JUnit that the public void method to which it is attached can be run
as a test case.
• @Before : Several tests need similar objects created before they can run. Annotating a public void
method with @Before causes that method to be run before each Test method.
• @After : If you allocate external resources in a Before method you need to release them after the test
runs. Annotating a public void method with @After causes that method to be run after the Test
method.
• @BeforeClass : Annotating a public static void method with @BeforeClass causes it to be run once
before any of the test methods in the class. This can be used to perform computationally expensive
setup (like logging into a database).
• @AfterClass : Will perform the method after all tests have finished. This can be used to perform clean-
up activities for example be used to disconnect to a database
• @Ignore : Sometimes you want to temporarily disable a test or a group of tests. Methods annotated
with Test that are also annotated with @Ignore will not be executed as tests. Also, you can annotate a
class containing test methods with @Ignore and none of the containing tests will be executed.
JUNIT LIFE CYCLE
ASSERTION
• All the assertion are in the Assert class.
public class Assert extends java.lang.Object
• This class provides a set of assertion methods useful for writing tests.
• Only failed assertions are recorded.
ASSERTION METHODS
• void assertEquals(boolean expected, boolean actual) Check that two primitives/Objects are equal
• void assertTrue(boolean expected, boolean actual) Check that a condition is true
• void assertFalse(boolean condition) Check that a condition is false
• void assertNotNull(Object object) Check that an object isn't null.
• void assertNull(Object object) Check that an object is null
ASSERTION METHODS (CONTD…)
• void assertSame(boolean condition) The assertSame() methods tests if two object references
point to the same object
• void assertNotSame(boolean condition) The assertNotSame() methods tests if two object
references not point to the same object
• void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test
whether two arrays are equal to each other.
• fail(String message) Fails a test with the given message.
• assertArrayEquals(String message,expected array,actual array) Asserts that two byte arrays are
equal. If they are not, an AssertionError is thrown with the given message.
JUNIT SET UP
• download the latest version of JUnit, referred as junit4.x.x.zip from given below link :
• http://sourceforge.net/projects/junit/files/
As step 2 Add the
downloaded junit jar
file and try to finish the
project creation
As step 1 Create a java
project
JAR FILES USED IN THE MENTIONED SAMPLES
API'S OF JUNIT
Class Name Functionality
Assert A set of assert methods.
TestCase A test case defines the fixture to run multiple tests.
TestResult A TestResult collects the results of executing a test case.
TestSuite A TestSuite is a Composite of Tests.
@TEST SAMPLE
package Test;
import static org.junit.Assert.*;
import org.junit.Test;
import Test.Pet;
public class PetTest {
@Test
public void testPet() {
}
@Test
public void testMeaow()
{
Pet testPet = new Pet();
assertTrue("Meaow".equals(testPet.meaow()));
}
}
package Test;
public class Pet {
public Pet() {}
public String meaow() {
return "Meaow";
}
}
junit-160729073220 eclipse software testing.pdf
junit-160729073220 eclipse software testing.pdf
CREATE A JAVA CLASS & TEST CLASS
• Create a class TestSamples.java
• Right click on TestSamples.java, select New ->others-->(Inside JUnit folder)JUnit Test case and select
Next button, the following window appears
package TestSamples;
public class TestSample {
public int multiply(int x, int y) {
return x * y;
}
}
Click Next
Select the check box
TestSample and click
Finish
• On clicking finish a new file named TestSampleTest.java gets created automatically and is as
follows
• Now edit the stub so as to make it assertive.
package TestSamples;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestSampleTest {
@Test
public void test() {
fail("Not yet implemented");
}
}
• After editing the stub, now the class file and its test case looks something like this
package TestSamples;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestSampleTest {
@Test
public void testMultiply() {
TestSample ts=new TestSample();
assertEquals(30,ts.multiply(5, 6));
}
}
EXECUTING A JUNIT TEST
• Right click on your new test class and select Run-As-> Junit Test.
• If the output shows green flag, your test is successful.
• If it shows red, it means class have some failures or errors.
• It will also show you the methods which has errors and the Failure Trace
• Both failure and successful scenarios are
displayed here for the same
CREATING A TEST SUITE
• Multiple tests can be combined into a test suite. All test in this test suite will then be executed if you
run the test suite.
• To create a new test suite, select your package, right mouse click->, select New->Others->Junit ->JUnit
Test Suite->next->Finish.
CREATING A TEST SUITE(CONTD…)
• As a result the following TestSuite is created
package Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ PetTest.class, TestCase.class, TestCase1.class,
TestClassMain.class, TestSuite.class, UnitTest.class })
public class AllTests {
}
junit-160729073220 eclipse software testing.pdf
TESTCASE CLASS
• org.junit.TestCase class id declared as follows.
• A test case defines the fixture to run multiple tests.
public abstract class TestCase extends Assert implements Test
FREQUENTLY USED METHODS FROM TESTCASE CLASS
• int countTestCases() Counts the number of test cases.
• TestResult createResult() Creates a default TestResult object.
• String getName() Gets the name of a TestCase.
• TestResult run() A convenience method to run this test.
• void run(TestResult result) Runs the test case and collects the results in TestResult.
• void setName(String name) Sets the name of a TestCase.
• void setUp() Sets up the fixture, for example, open a database connection.
• void tearDown() Tears down the fixture, for example, close a database connection.
• String toString() Returns a string representation of the test case.
package TestSamples;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
public class TestJunit extends TestCase {
protected double fValue1;
protected double fValue2;
@Before
public void setUp() {
System.out.println("setup");
fValue1= 8.0;
fValue2= 9.0;
}
@Test
public void testCaseAdd() {
//count the number of test cases
System.out.println("No of Test Case = "+ this.countTestCases());
//test getName
String name= this.getName();
System.out.println("Test Case Name = "+ name);
//test setName
this.setName("testCaseAddNew");
String newName= this.getName();
System.out.println("Updated Test Case Name = "+ newName);
assertEquals(5.0, fValue1+fValue2);
}}
TESTCASE CLASS EXAMPLE
package TestSamples;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class Main {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Output:
setup
No of Test Case = 1
Test Case Name = testCaseAdd
Updated Test Case Name = testCaseAddNew
testCaseAddNew(TestSamples.TestJunit): expected:<5.0> but was:<17.0>
false
JUNIT TESTRESULT
• TestResult collects the results of executing a test case.
TestResult Class
• The declaration for org.junit.TestResult class:
• A failure is anticipated and checked for with assertions.
• Errors are unanticipated problems such as ArrayIndexOutOfBoundsException.
public class TestResult extends Object
FREQUENTLY USED METHODS FROM TESTRESULT CLASS.
• void addError(Test test, Throwable t) Adds an error to the list of errors.
• void addFailure(Test test, AssertionFailedError t) Adds a failure to the list of failures.
• void endTest(Test test) Informs the result that a test was completed.
• int errorCount() Gets the number of detected errors.
• Enumeration<TestFailure> errors() Returns an Enumeration for the errors.
• int failureCount() Gets the number of detected failures.
• void run(TestCase test) Runs a TestCase.
• int int runCount() Gets the number of run tests.
• void startTest(Test test) Informs the result that a test will be started.
• void stop() Marks that the test run should stop.
TESTING FOR EXCEPTIONS IN JUNIT
• The Test annotation supports 'expected' parameters which declares that a test method should
throw an exception. If it doesn't throw an exception or if it throws a different exception than the one
declared, the test fails.
• For example, the following test succeeds :
JUNIT ANNOTATION IMPLEMENTATION COMPLETE
EXAMPLE
• Junit Annotation Class : AnnotTest.java
• Test Runner Class : AnnotTestRunner.java
Source code and its out are displayed in the following slides
package 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;
public class AnnotTest {
@BeforeClass
public static void beforeClass() {
System.out.println("in before class");
}
@AfterClass
public static void afterClass() {
System.out.println("in after class");
}
@Before
public void before() {
System.out.println("in before");
}
@After
public void after() {
System.out.println("in after");
}
@Test
public void test() {
System.out.println("in test");
}
@Ignore
public void ignoreTest() {
System.out.println("in ignore test");
}
}
package Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class AnnotTestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(AnnotTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Output:
in before class
in before
in test
in after
in after class
true
ORGANIZING TEST FIXTURES WITH SETUP/TEARDOWN AND
@BEFORE/ @AFTER
• JUnit test runners automatically invoke the setUp() method before running each test. This method
typically initializes fields, turns on logging, resets environment variables, and so forth.
• JUnit test runners automatically invoke the tearDown() method after running each test which
releases above mention resources after test.
• Annotating a public void method with @Before causes that method to be run before the Test
method.
• Annotating a public void method with @After causes that method to be run after the Test method.
• Annotating a public static void method with @BeforeClass causes it to be run once before any of the
test methods in the class.
• Annotating a public static void method with @AfterClass causes it to be run after all tests have
finished.
The methods will execute in the following order:
• oneTimeSetUp()
• setUp()
• testEmptyCollection()
• tearDown()
• setUp()
• testOneItemCollection()
• tearDown()
• OneTimeTearDown()
A COMPLETE EXAMPLE OF JUNIT TESTING
• Pojo class : Student.java
• Business Logic : StudentDetails.java
• Test Case class : StudentDetailsTest.java
• Main Class : StudentMain.java
package Testing;
public class Student {
private String name;
private String city;
private int age;
private int percentage;
}
package Testing;
public class StudentDetails {
public String calculatePercentage(Student student){
String status;
if(student.getPercentage() < 50){
status = "Fail";
}else{
status = "Pass";
}
return status;
}
}
package Testing;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StudentDetailsTest {
StudentDetails studentDetails =new StudentDetails();
Student student = new Student();
@Test
public void CalculatePercentage() {
student.setName("Derick");
student.setAge(25);
student.setCity("Agra");
student.setPercentage(79);
String status=studentDetails.calculatePercentage(student);
assertEquals("Fail", status, "Fail");
}
}
package Testing;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class StudentMain {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(StudentDetailsTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
junit-160729073220 eclipse software testing.pdf
JUNIT TIME TEST
• Junit has a handy option of Timeout.
• If a test case takes more time than specified milliseconds then Junit will automatically mark it as failed.
• The timeout parameter is used along with @Test annotation.
package Test;
import static org.junit.Assert.*;
import org.junit.Test;
import Test.Pet;
public class PetTest {
@Test
public void testPet() {
}
@Test (timeout=5000)
public void testMeaow()
{
Pet testPet = new Pet();
assertTrue("Meaow".equals(testPet.meaow()));
}
}
package Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class AnnotTestRunner {
public static void main(String[] args) {
Result result =
JUnitCore.runClasses(PetTest.class);
for (Failure failure :
result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Output: true
THANK YOU…

More Related Content

PPTX
Introduction to JUnit
PPTX
PDF
TestNG introduction
PPTX
Qt test framework
 
PDF
An Introduction to Unit Test Using NUnit
DOCX
JUnit_Guide_Expanded_Presentation[1].docx
DOCX
JUnit_Guide_Expanded_Presentation[1].docx............................
Introduction to JUnit
TestNG introduction
Qt test framework
 
An Introduction to Unit Test Using NUnit
JUnit_Guide_Expanded_Presentation[1].docx
JUnit_Guide_Expanded_Presentation[1].docx............................

Similar to junit-160729073220 eclipse software testing.pdf (20)

DOCX
JUnit_Guide_Expanded_Presentation[1].docx
PDF
Testing Angular
PPTX
PPTX
8-testing.pptx
PPTX
Software Testing and JUnit and Best Practices
PPTX
Testing with Junit4
PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
PPTX
Unit testing
PDF
Unit testing with Junit
PPT
Intro to junit
PPT
PPTX
JUnit Test Case With Processminer modules.pptx
PPTX
Session 4 -Junit- Testing Exceptions, Junit hooks.pptx
PDF
Test driven development
PPTX
unit 1 (1).pptx
PPTX
Lecture (Software Testing).pptx
DOCX
Test Driven Development
PPTX
Unit Testng with PHP Unit - A Step by Step Training
PPT
Unit testing with java
JUnit_Guide_Expanded_Presentation[1].docx
Testing Angular
8-testing.pptx
Software Testing and JUnit and Best Practices
Testing with Junit4
2.Python_Testing_Using_PyUnit_PyTest.pptx
Unit testing
Unit testing with Junit
Intro to junit
JUnit Test Case With Processminer modules.pptx
Session 4 -Junit- Testing Exceptions, Junit hooks.pptx
Test driven development
unit 1 (1).pptx
Lecture (Software Testing).pptx
Test Driven Development
Unit Testng with PHP Unit - A Step by Step Training
Unit testing with java
Ad

More from KomalSinghGill (11)

PDF
Software requirement specifications document.pdf
PDF
testplan software testing planing tests.pdf
PPTX
Introduction_to_Maven eclipse sw testing.pptx
PPT
2. Lect 27 to 28 White box s/w testing.ppt
PPTX
Introduction_to_Maven software testing.pptx
PPTX
Software Testing life cycle presentation.pptx
PPTX
basic software testing principles and obectives.pptx
PPT
Ackerman-p99.ppt
PPT
9-Coding.ppt
PPT
6&8-Design.ppt
PDF
Process Modelling and DFD.pdf
Software requirement specifications document.pdf
testplan software testing planing tests.pdf
Introduction_to_Maven eclipse sw testing.pptx
2. Lect 27 to 28 White box s/w testing.ppt
Introduction_to_Maven software testing.pptx
Software Testing life cycle presentation.pptx
basic software testing principles and obectives.pptx
Ackerman-p99.ppt
9-Coding.ppt
6&8-Design.ppt
Process Modelling and DFD.pdf
Ad

Recently uploaded (20)

PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Construction Project Organization Group 2.pptx
PDF
Digital Logic Computer Design lecture notes
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
web development for engineering and engineering
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Well-logging-methods_new................
PPTX
Geodesy 1.pptx...............................................
PPTX
Sustainable Sites - Green Building Construction
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
OOP with Java - Java Introduction (Basics)
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Lecture Notes Electrical Wiring System Components
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Construction Project Organization Group 2.pptx
Digital Logic Computer Design lecture notes
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
web development for engineering and engineering
additive manufacturing of ss316l using mig welding
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Well-logging-methods_new................
Geodesy 1.pptx...............................................
Sustainable Sites - Green Building Construction
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk

junit-160729073220 eclipse software testing.pdf

  • 2. HISTORY • Kent Beck developed the first xUnit automated test tool for Smalltalk in mid-90’s • Beck and Gamma (of design patterns Gang of Four) developed JUnit on a flight from Zurich to Washington, D.C. • Martin Fowler: “Never in the field of software development was so much owed by so many to so few lines of code.” • Junit has become the standard tool for Test-Driven Development in Java • Junit test generators now part of many Java IDEs (Eclipse, BlueJ, Jbuilder, DrJava) • Xunit tools have since been developed for many other languages (Perl, C++, Python, Visual Basic, C#, …)
  • 3. UNIT TESTING • Unit Testing is one of the phase of software development process in which units(smallest part of the application) are separately examined for proper operation. • Generally programmers and occasionally white box testers created unit tests. • Its implementation can vary from being very manual (pencil and paper) to being formalized as part of build automation.
  • 4. TESTS THAT ARE PERFORMED DURING THE UNIT TESTING ARE EXPLAINED BELOW • Module Interface test: In module interface test, it is checked whether the information is properly flowing in to the program unit (or module) and properly happen out of it or not. • Local data structures: These are tested to inquiry if the local data within the module is stored properly or not. • Boundary conditions: It is observed that much software often fails at boundary related conditions. That’s why boundary related conditions are always tested to make safe that the program is properly working at its boundary condition’s. • Independent paths: All independent paths are tested to see that they are properly executing their task and terminating at the end of the program. • Error handling paths: These are tested to review if errors are handled properly by them or not.
  • 5. FAMOUS JAVA UNIT TESTING TOOLS • JMockit • Artima SuiteRunner • Cactus • Checkstyle • Cobertura • Continuous Testing • Daedalos JUnit Extensions • Dbunit • DDSteps • Jete • Jetif • JFCUnit • Jiffie • jMock • JOSIT • JsTester • JSystem • DepUnit • djUnit • Dumbster • EasyMock + ClassExtension • EclEmma • Ejb3unit • Emma • Feed4JUnit • Fest • Findbugs • Gretel • GroboUtils • Hansel 1.0 • Haste • J2ME Unit Testing Toolkit • Jacareto
  • 6. FAMOUS JAVA UNIT TESTING TOOLS • JUnitPerf • JXUnit • Macker • Mockito • MockObjects • Mockrunner • MoMEUnit • moreUnit • NoUnit • TestGen4J • TestNG • UISpec4J • Unitils • XHTMLUnit • Xtest • Fest • Findbugs • Gretel • Pisces • PMD • Quilt • Slim • Sonar • StrutsTestCase for JUnit v1.9.5 • T2 • TagUnit • Testare • GroboUtils • Hansel 1.0 • Haste • J2ME Unit Testing Toolkit • Jailer • JDepend • JEasyTest • JellyUnit • Jester • JTestCase • Jumble • JUnit • JUnit-addons • JUnitDoclet • JUnitEE
  • 7. JUNIT • It is part of unit testing frameworks family collectively known as xUnit. Other examples are CPPUnit, PHPUnit, JSUnit etc. • JUnit is linked as a JAR at compile-time; the framework resides under packagesjunit.framework for JUnit 3.8 and earlier and under org.junit for JUnit 4 and later. • JUnit has now become the standard tool for Test-Driven Development in Java. • JUnit test generators now part of many Java IDEs (Eclipse, BlueJ, Jbuilder, DrJava etc).
  • 8. JUNIT (CONTD…) • JUnit provides Annotation to identify the test methods and utility methods to assert expected results. • JUnit has Test runners for running tests. • JUnit tests can be organized into test suites which contains test cases and other test suites. • JUnit Framework can be easily integrated with either of the followings: • Eclipse • Ant • Maven
  • 9. TESTING VIA JUNIT • Can test JUnit by using Test Case & Test Suit . • Test Case: A Test Case is a java class which is used to test a single class. • Test Suite :A Test Suit is a java class which contains many test cases or java classes to test together in a single run.
  • 10. BENEFITS • Simple framework for writing automated, self-verifying tests in Java • Support for test assertions • Test suite development • Immediate test reporting
  • 11. FEATURES • Annotation to identify the test methods(After JUnit 4 ). • Assertions for testing expected results. • Test fixtures for sharing common test data. • Test runners for running tests. • Aggregating tests using suites.
  • 12. NEED OF JUNIT • JUnit tests allow you to write code faster while increasing quality. • JUnit is elegantly simple. It is less complex & takes less time. • JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results. • JUnit tests can be organized into test suites containing test cases and even other test suites. • Writing JUnit tests is inexpensive.
  • 13. JUNIT ANNOTATIONS • @Test : The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. • @Before : Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method. • @After : If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. • @BeforeClass : Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class. This can be used to perform computationally expensive setup (like logging into a database). • @AfterClass : Will perform the method after all tests have finished. This can be used to perform clean- up activities for example be used to disconnect to a database • @Ignore : Sometimes you want to temporarily disable a test or a group of tests. Methods annotated with Test that are also annotated with @Ignore will not be executed as tests. Also, you can annotate a class containing test methods with @Ignore and none of the containing tests will be executed.
  • 15. ASSERTION • All the assertion are in the Assert class. public class Assert extends java.lang.Object • This class provides a set of assertion methods useful for writing tests. • Only failed assertions are recorded.
  • 16. ASSERTION METHODS • void assertEquals(boolean expected, boolean actual) Check that two primitives/Objects are equal • void assertTrue(boolean expected, boolean actual) Check that a condition is true • void assertFalse(boolean condition) Check that a condition is false • void assertNotNull(Object object) Check that an object isn't null. • void assertNull(Object object) Check that an object is null
  • 17. ASSERTION METHODS (CONTD…) • void assertSame(boolean condition) The assertSame() methods tests if two object references point to the same object • void assertNotSame(boolean condition) The assertNotSame() methods tests if two object references not point to the same object • void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other. • fail(String message) Fails a test with the given message. • assertArrayEquals(String message,expected array,actual array) Asserts that two byte arrays are equal. If they are not, an AssertionError is thrown with the given message.
  • 18. JUNIT SET UP • download the latest version of JUnit, referred as junit4.x.x.zip from given below link : • http://sourceforge.net/projects/junit/files/
  • 19. As step 2 Add the downloaded junit jar file and try to finish the project creation As step 1 Create a java project
  • 20. JAR FILES USED IN THE MENTIONED SAMPLES
  • 21. API'S OF JUNIT Class Name Functionality Assert A set of assert methods. TestCase A test case defines the fixture to run multiple tests. TestResult A TestResult collects the results of executing a test case. TestSuite A TestSuite is a Composite of Tests.
  • 22. @TEST SAMPLE package Test; import static org.junit.Assert.*; import org.junit.Test; import Test.Pet; public class PetTest { @Test public void testPet() { } @Test public void testMeaow() { Pet testPet = new Pet(); assertTrue("Meaow".equals(testPet.meaow())); } } package Test; public class Pet { public Pet() {} public String meaow() { return "Meaow"; } }
  • 25. CREATE A JAVA CLASS & TEST CLASS • Create a class TestSamples.java • Right click on TestSamples.java, select New ->others-->(Inside JUnit folder)JUnit Test case and select Next button, the following window appears package TestSamples; public class TestSample { public int multiply(int x, int y) { return x * y; } }
  • 26. Click Next Select the check box TestSample and click Finish
  • 27. • On clicking finish a new file named TestSampleTest.java gets created automatically and is as follows • Now edit the stub so as to make it assertive. package TestSamples; import static org.junit.Assert.*; import org.junit.Test; public class TestSampleTest { @Test public void test() { fail("Not yet implemented"); } }
  • 28. • After editing the stub, now the class file and its test case looks something like this package TestSamples; import static org.junit.Assert.*; import org.junit.Test; public class TestSampleTest { @Test public void testMultiply() { TestSample ts=new TestSample(); assertEquals(30,ts.multiply(5, 6)); } }
  • 29. EXECUTING A JUNIT TEST • Right click on your new test class and select Run-As-> Junit Test. • If the output shows green flag, your test is successful. • If it shows red, it means class have some failures or errors. • It will also show you the methods which has errors and the Failure Trace
  • 30. • Both failure and successful scenarios are displayed here for the same
  • 31. CREATING A TEST SUITE • Multiple tests can be combined into a test suite. All test in this test suite will then be executed if you run the test suite. • To create a new test suite, select your package, right mouse click->, select New->Others->Junit ->JUnit Test Suite->next->Finish.
  • 32. CREATING A TEST SUITE(CONTD…) • As a result the following TestSuite is created package Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ PetTest.class, TestCase.class, TestCase1.class, TestClassMain.class, TestSuite.class, UnitTest.class }) public class AllTests { }
  • 34. TESTCASE CLASS • org.junit.TestCase class id declared as follows. • A test case defines the fixture to run multiple tests. public abstract class TestCase extends Assert implements Test
  • 35. FREQUENTLY USED METHODS FROM TESTCASE CLASS • int countTestCases() Counts the number of test cases. • TestResult createResult() Creates a default TestResult object. • String getName() Gets the name of a TestCase. • TestResult run() A convenience method to run this test. • void run(TestResult result) Runs the test case and collects the results in TestResult. • void setName(String name) Sets the name of a TestCase. • void setUp() Sets up the fixture, for example, open a database connection. • void tearDown() Tears down the fixture, for example, close a database connection. • String toString() Returns a string representation of the test case.
  • 36. package TestSamples; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; public class TestJunit extends TestCase { protected double fValue1; protected double fValue2; @Before public void setUp() { System.out.println("setup"); fValue1= 8.0; fValue2= 9.0; } @Test public void testCaseAdd() { //count the number of test cases System.out.println("No of Test Case = "+ this.countTestCases()); //test getName String name= this.getName(); System.out.println("Test Case Name = "+ name); //test setName this.setName("testCaseAddNew"); String newName= this.getName(); System.out.println("Updated Test Case Name = "+ newName); assertEquals(5.0, fValue1+fValue2); }} TESTCASE CLASS EXAMPLE
  • 37. package TestSamples; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class Main { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Output: setup No of Test Case = 1 Test Case Name = testCaseAdd Updated Test Case Name = testCaseAddNew testCaseAddNew(TestSamples.TestJunit): expected:<5.0> but was:<17.0> false
  • 38. JUNIT TESTRESULT • TestResult collects the results of executing a test case. TestResult Class • The declaration for org.junit.TestResult class: • A failure is anticipated and checked for with assertions. • Errors are unanticipated problems such as ArrayIndexOutOfBoundsException. public class TestResult extends Object
  • 39. FREQUENTLY USED METHODS FROM TESTRESULT CLASS. • void addError(Test test, Throwable t) Adds an error to the list of errors. • void addFailure(Test test, AssertionFailedError t) Adds a failure to the list of failures. • void endTest(Test test) Informs the result that a test was completed. • int errorCount() Gets the number of detected errors. • Enumeration<TestFailure> errors() Returns an Enumeration for the errors. • int failureCount() Gets the number of detected failures. • void run(TestCase test) Runs a TestCase. • int int runCount() Gets the number of run tests. • void startTest(Test test) Informs the result that a test will be started. • void stop() Marks that the test run should stop.
  • 40. TESTING FOR EXCEPTIONS IN JUNIT • The Test annotation supports 'expected' parameters which declares that a test method should throw an exception. If it doesn't throw an exception or if it throws a different exception than the one declared, the test fails. • For example, the following test succeeds :
  • 41. JUNIT ANNOTATION IMPLEMENTATION COMPLETE EXAMPLE • Junit Annotation Class : AnnotTest.java • Test Runner Class : AnnotTestRunner.java Source code and its out are displayed in the following slides
  • 42. package 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; public class AnnotTest { @BeforeClass public static void beforeClass() { System.out.println("in before class"); } @AfterClass public static void afterClass() { System.out.println("in after class"); } @Before public void before() { System.out.println("in before"); } @After public void after() { System.out.println("in after"); } @Test public void test() { System.out.println("in test"); } @Ignore public void ignoreTest() { System.out.println("in ignore test"); } }
  • 43. package Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class AnnotTestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(AnnotTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Output: in before class in before in test in after in after class true
  • 44. ORGANIZING TEST FIXTURES WITH SETUP/TEARDOWN AND @BEFORE/ @AFTER • JUnit test runners automatically invoke the setUp() method before running each test. This method typically initializes fields, turns on logging, resets environment variables, and so forth. • JUnit test runners automatically invoke the tearDown() method after running each test which releases above mention resources after test. • Annotating a public void method with @Before causes that method to be run before the Test method. • Annotating a public void method with @After causes that method to be run after the Test method. • Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class. • Annotating a public static void method with @AfterClass causes it to be run after all tests have finished.
  • 45. The methods will execute in the following order: • oneTimeSetUp() • setUp() • testEmptyCollection() • tearDown() • setUp() • testOneItemCollection() • tearDown() • OneTimeTearDown()
  • 46. A COMPLETE EXAMPLE OF JUNIT TESTING • Pojo class : Student.java • Business Logic : StudentDetails.java • Test Case class : StudentDetailsTest.java • Main Class : StudentMain.java package Testing; public class Student { private String name; private String city; private int age; private int percentage; } package Testing; public class StudentDetails { public String calculatePercentage(Student student){ String status; if(student.getPercentage() < 50){ status = "Fail"; }else{ status = "Pass"; } return status; } }
  • 47. package Testing; import org.junit.Test; import static org.junit.Assert.assertEquals; public class StudentDetailsTest { StudentDetails studentDetails =new StudentDetails(); Student student = new Student(); @Test public void CalculatePercentage() { student.setName("Derick"); student.setAge(25); student.setCity("Agra"); student.setPercentage(79); String status=studentDetails.calculatePercentage(student); assertEquals("Fail", status, "Fail"); } }
  • 48. package Testing; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class StudentMain { public static void main(String[] args) { Result result = JUnitCore.runClasses(StudentDetailsTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
  • 50. JUNIT TIME TEST • Junit has a handy option of Timeout. • If a test case takes more time than specified milliseconds then Junit will automatically mark it as failed. • The timeout parameter is used along with @Test annotation.
  • 51. package Test; import static org.junit.Assert.*; import org.junit.Test; import Test.Pet; public class PetTest { @Test public void testPet() { } @Test (timeout=5000) public void testMeaow() { Pet testPet = new Pet(); assertTrue("Meaow".equals(testPet.meaow())); } } package Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class AnnotTestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(PetTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Output: true