Java Jun It
-
Upload
bandi-shankar -
Category
Documents
-
view
220 -
download
0
Transcript of Java Jun It
-
8/6/2019 Java Jun It
1/58
1
JUnit Testing FrameworkJUnit Testing Framework
-
8/6/2019 Java Jun It
2/58
Topics What is and Why JUnit framework?What is and Why JUnit framework?
JUnit mechanicsJUnit mechanics
FixturesFixtures
Test suitesTest suites
Test runnersTest runners
JUnit classesJUnit classes
Best practice guidelinesBest practice guidelines
Design patterns for testingDesign patterns for testing
ExtensionsExtensions
-
8/6/2019 Java Jun It
3/58
3
Test-Driven DevelopmentTest-Driven Development
(TDD)(TDD)
-
8/6/2019 Java Jun It
4/58
Acknowledgment This presentation is a modified (andThis presentation is a modified (and
enhanced) version of Orlando Java User'senhanced) version of Orlando Java User'sGroup presentation on the same subjectGroup presentation on the same subject
byby Matt Weber
-
8/6/2019 Java Jun It
5/58
Why test?
Automated tests prove featuresAutomated tests prove features
Tests retain their value over time andTests retain their value over time and
allows others to prove the software stillallows others to prove the software stillworks (as tested).works (as tested).
Confidence, quality, sleepConfidence, quality, sleep
Get to code sooner by writing tests.Get to code sooner by writing tests.
-
8/6/2019 Java Jun It
6/58
Test-Driven Development (TDD)
Is a software development techniqueIs a software development technique
that involves repeatedly first writing athat involves repeatedly first writing a
test case and then implementing only thetest case and then implementing only the
code necessary to pass the testcode necessary to pass the test
Gives rapid feedbackGives rapid feedback
-
8/6/2019 Java Jun It
7/58
Unit Testing
Is a procedure used to validate thatIs a procedure used to validate that
individual units of source code areindividual units of source code are
working properlyworking properly
A unit is the smallest testable part of anA unit is the smallest testable part of an
applicationapplication
In procedural programming a unit may be anIn procedural programming a unit may be an
individual program, function, procedure, webindividual program, function, procedure, webpage, menu etc, while in object-orientedpage, menu etc, while in object-oriented
programming, the smallest unit is always aprogramming, the smallest unit is always a
Class; which may be a base/super class,Class; which may be a base/super class,
abstract class or derived/child classabstract class or derived/child class
-
8/6/2019 Java Jun It
8/588
What is and WhyWhat is and Why
JUnit Testing Framework?JUnit Testing Framework?
-
8/6/2019 Java Jun It
9/58
What is JUnit?
JUnit is a regression testing frameworkJUnit is a regression testing framework
Used by developers to implement unitUsed by developers to implement unittests in Java (de-facto standard)tests in Java (de-facto standard)
Integrated with AntIntegrated with Ant
Testing is performed as part of nightly buildTesting is performed as part of nightly build
processprocess
Goal: Accelerate programming andGoal: Accelerate programming andincrease the quality of code.increase the quality of code.
Part of XUnit family (HTTPUnit, Cactus),Part of XUnit family (HTTPUnit, Cactus),
CppUnitCppUnit
-
8/6/2019 Java Jun It
10/58
Why JUnit?
Without JUnit, you will have to useWithout JUnit, you will have to use
println() to print out some resultprintln() to print out some result
No explicit concept of test passing or failureNo explicit concept of test passing or failure
No mechanism to collect results in aNo mechanism to collect results in a
structured fashionstructured fashion
No replicabilityNo replicability
JUnit addresses all these issuesJUnit addresses all these issues
-
8/6/2019 Java Jun It
11/58
Key Goals of JUnit Easy to use to create testsEasy to use to create tests
Create tests that retain their value over timeCreate tests that retain their value over time
Leverage existing tests to write new onesLeverage existing tests to write new ones(reusable)(reusable)
-
8/6/2019 Java Jun It
12/58
What does JUnit provide? API for easily creating Java test casesAPI for easily creating Java test cases
Comprehensive assertion facilitiesComprehensive assertion facilities
verifyverify
expected versus actual resultsexpected versus actual results
Test runners for running testsTest runners for running tests
Aggregation facility (test suites)Aggregation facility (test suites)
ReportingReporting
-
8/6/2019 Java Jun It
13/58
13
How to Write JUnitHow to Write JUnit
Testing Code?Testing Code?
-
8/6/2019 Java Jun It
14/58
How to write JUnit-based
testing code (Minimum) Include JUnit.jar in the classpathInclude JUnit.jar in the classpath
Define a subclass ofDefine a subclass ofTestCaseTestCase classclass
Define one or more publicDefine one or more publictestXXX()testXXX()methods in the subclassmethods in the subclass
Write assert methods inside the testXXXWrite assert methods inside the testXXX
methods()methods() Optionally defineOptionally definemain()main()totorun therun the
TestCase in standalone modeTestCase in standalone mode
-
8/6/2019 Java Jun It
15/58
Test methods
Test methods has name patternTest methods has name pattern
testXXX()testXXX()
XXX reflects the method of the target classXXX reflects the method of the target class
Test methods must have no argumentsTest methods must have no arguments
Test methods are type of voidTest methods are type of void
-
8/6/2019 Java Jun It
16/58
Example 1: Very Simple Test
import junit.framework.TestCase;import junit.framework.TestCase;
public class SimpleTest extends TestCase {public class SimpleTest extends TestCase {
public SimpleTest(String name) {public SimpleTest(String name) {
super(name);super(name);
}}// Test code// Test code
public void testSomething() {public void testSomething() {
System.out.println("About to call assertTrue() method...");System.out.println("About to call assertTrue() method...");
assertTrue(4 == (2 * 2));assertTrue(4 == (2 * 2));
}}
// You don't have to have main() method, use Test runner// You don't have to have main() method, use Test runner
public static void main(String[] args){public static void main(String[] args){
junit.textui.TestRunner.run(SimpleTest.class);junit.textui.TestRunner.run(SimpleTest.class);
}}
}}
-
8/6/2019 Java Jun It
17/58
How to write JUnit-based testing
code (More Sophisticated) Optionally override the setUp() &Optionally override the setUp() &
tearDown()methodstearDown()methods
Create common test dataCreate common test data
Optionally define a static suite()factoryOptionally define a static suite()factory
methodmethod
Create a TestSuite containing all the tests.Create a TestSuite containing all the tests.
-
8/6/2019 Java Jun It
18/58
-
8/6/2019 Java Jun It
19/58
Example 2: Simple Testcase (cont.)// Create TestSuite object// Create TestSuite objectpublic static Test suite (){public static Test suite (){
suite = new TestSuite (StringTest");suite = new TestSuite (StringTest");String tests = System.getProperty("tests");String tests = System.getProperty("tests");if (tests == null){if (tests == null){suite.addTest(newsuite.addTest(new
TestSuite(StringTest.class));TestSuite(StringTest.class));}else{}else{StringTokenizer tokens = newStringTokenizer tokens = new
StringTokenizer(tests, ",");StringTokenizer(tests, ",");while (tokens.hasMoreTokens()){while (tokens.hasMoreTokens()){
suite.addTest(newsuite.addTest(newStringTest((String)tokens.nextToken()));StringTest((String)tokens.nextToken()));
}}}}return suite;return suite;
}}
-
8/6/2019 Java Jun It
20/58
-
8/6/2019 Java Jun It
21/58
Assert statements JUnit Assertions are methods starting withJUnit Assertions are methods starting with
assertassert
Determines theDetermines the success or failuresuccess or failure of a testof a test
AnAnassertassertis simply ais simply a comparisoncomparison betweenbetweenanan expectedexpected value and anvalue and an actualactual valuevalue
Two variantsTwo variants
assertXXX(...)assertXXX(...)
assertXXX(String message, ...) - the message isassertXXX(String message, ...) - the message is
displayed when the assertXXX() failsdisplayed when the assertXXX() fails
-
8/6/2019 Java Jun It
22/58
Assert statements Asserts that a condition is trueAsserts that a condition is true
assertTrue(boolean condition)assertTrue(boolean condition)
assertTrue(String message, boolean condition)assertTrue(String message, boolean condition)
Asserts that a condition is falseAsserts that a condition is false
assertFalse(boolean condition)assertFalse(boolean condition)
assertFalse(String message, boolean condition)assertFalse(String message, boolean condition)
-
8/6/2019 Java Jun It
23/58
Assert statements Asserts expected.equals(actual)Asserts expected.equals(actual)behaviorbehavior
assertEquals(expected, actual)assertEquals(expected, actual)
assertEquals(String message, expected, actual)assertEquals(String message, expected, actual)
Asserts expected == actualAsserts expected == actualbehaviorbehavior assertSame(Object expected, Object actual)assertSame(Object expected, Object actual)
assertSame(String message, Object expected,assertSame(String message, Object expected,
Object actual)Object actual)
-
8/6/2019 Java Jun It
24/58
Assert statements Asserts object reference is nullAsserts object reference is null
assertNull(Object obj)assertNull(Object obj)
assertNull(String message, Object obj)assertNull(String message, Object obj)
Asserts object reference is not nullAsserts object reference is not null
assertNotNull(Object obj)assertNotNull(Object obj)
assertNotNull(String message, Object obj)assertNotNull(String message, Object obj)
Forces a failureForces a failure fail()fail()
fail(String message)fail(String message)
-
8/6/2019 Java Jun It
25/58
25
FixturesFixtures
-
8/6/2019 Java Jun It
26/58
Fixtures
setUp() and tearDown() used to initializesetUp() and tearDown() used to initialize
and release common test dataand release common test data
setUp() is run before every test invocation &setUp() is run before every test invocation &tearDown() is run after every test methodtearDown() is run after every test method
-
8/6/2019 Java Jun It
27/58
Example: setUp
public class MathTest extends TestCase {public class MathTest extends TestCase {protected double fValue1, fValue2;protected double fValue1, fValue2;
protected void setUp() {protected void setUp() {
fValue1= 2.0;fValue1= 2.0;
fValue2= 3.0;fValue2= 3.0;
}}
public void testAdd() {public void testAdd() {
double result= fValue1 + fValue2;double result= fValue1 + fValue2;
assertTrue(result == 5.0);assertTrue(result == 5.0);
}}
public void testMultiply() {public void testMultiply() {
double result= fValue1 * fValue2;double result= fValue1 * fValue2;
assertTrue(result == 6.0);assertTrue(result == 6.0);
}}
-
8/6/2019 Java Jun It
28/58
28
Test SuitesTest Suites
-
8/6/2019 Java Jun It
29/58
Test Suites
Used to collect all the test casesUsed to collect all the test cases
Suites can contain testCases and testSuitesSuites can contain testCases and testSuites
TestSuite(java.lang.Class theClass,TestSuite(java.lang.Class theClass,))
addTest(Test test) oraddTest(Test test) or
addTestSuite(java.lang.Class testClass)addTestSuite(java.lang.Class testClass)
Suites can have hierararchySuites can have hierararchy
-
8/6/2019 Java Jun It
30/58
Example: Test Suitespublic static void main (String [] args){public static void main (String [] args){
junit.textui.TestRunner.run (suite ());junit.textui.TestRunner.run (suite ());
}}
public static Test suite (){public static Test suite (){
suite = new TestSuite ("AllTests");suite = new TestSuite ("AllTests");suite.addTestsuite.addTest
(new TestSuite (AllTests.class));(new TestSuite (AllTests.class));
suite.addTest (StringTest.suite());suite.addTest (StringTest.suite());
}}
public void testAllTests () throws Exception{public void testAllTests () throws Exception{
assertTrue (suite != null);assertTrue (suite != null);
}}
-
8/6/2019 Java Jun It
31/58
Example: Test Suitespublic static Test suite() {public static Test suite() {
TestSuite suite = new TestSuite(IntTest.class);TestSuite suite = new TestSuite(IntTest.class);
suite.addTest(new TestSuite(FloatTest.class));suite.addTest(new TestSuite(FloatTest.class));
suite.addTest(new TestSuite(BoolTest.class));suite.addTest(new TestSuite(BoolTest.class));
return suite;return suite;}}
-
8/6/2019 Java Jun It
32/58
-
8/6/2019 Java Jun It
33/58
TestRunners
TextText
Lightweight, quick quietLightweight, quick quiet
Run from command lineRun from command linejava StringTestjava StringTest
..............
Time: 0.05Time: 0.05
Tests run: 7, Failures: 0, Errors: 0Tests run: 7, Failures: 0, Errors: 0
-
8/6/2019 Java Jun It
34/58
TestRunners - SwingTestRunners - Swing Run with java junit.swingui.TestRunnerRun with java junit.swingui.TestRunner
-
8/6/2019 Java Jun It
35/58
Automating testing (Ant)
JUnit Task
-
8/6/2019 Java Jun It
36/58
Ant Batch mode
-
8/6/2019 Java Jun It
37/58
37
JUnit ClassesJUnit Classes
-
8/6/2019 Java Jun It
38/58
-
8/6/2019 Java Jun It
39/58
39
Best PracticeBest Practice
-
8/6/2019 Java Jun It
40/58
What should I test?
Tests things which could breakTests things which could break
Tests should succeed quietly.Tests should succeed quietly.
Dont print Doing foodone with foo!Dont print Doing foodone with foo!
Negative tests, exceptions and errorsNegative tests, exceptions and errors
What shouldnt I testWhat shouldnt I test Dont test set/get methodsDont test set/get methods
Dont test the compilerDont test the compiler
-
8/6/2019 Java Jun It
41/58
Test first and what to test
Write your test first, or at least at theWrite your test first, or at least at thesame timesame time
Test what can breakTest what can break
Create new tests to show bugs then fixCreate new tests to show bugs then fixthe bugthe bug
Test driven development says write theTest driven development says write thetest then make it pass by coding to it.test then make it pass by coding to it.
-
8/6/2019 Java Jun It
42/58
Testing for Exceptions
public void testExpectException()
{
String s1 = null;String s2 = new String("abcd");
try{s1.toString();fail("Should see null pointer");
}
catch(NullPointerException ex){
assertTrue(true);}
}
-
8/6/2019 Java Jun It
43/58
Test then Fix
Bugs occasionally slip through (gasp!)Bugs occasionally slip through (gasp!)
Write a test first which demonstrates theWrite a test first which demonstrates the
error. Obviously, this test is needed.error. Obviously, this test is needed.
Now, fix the bug and watch the bar goNow, fix the bug and watch the bar go
green!green!
Your tests assure the bug wontYour tests assure the bug wont
reappear.reappear.
-
8/6/2019 Java Jun It
44/58
Test then RefactorTest then Refactor
Once the code is written you want toOnce the code is written you want to
improve it.improve it.
Changes for performance,Changes for performance,maintainability, readability.maintainability, readability.
Tests help you make sure you dontTests help you make sure you dont
break it while improving it.break it while improving it.
Small change, test, small change, test...Small change, test, small change, test...
-
8/6/2019 Java Jun It
45/58
45
Design Patterns forDesign Patterns for
TestingTesting
-
8/6/2019 Java Jun It
46/58
Designing for testing
Separation of interface and implementationSeparation of interface and implementation
Allows substitution of implementation to testsAllows substitution of implementation to tests
Factory patternFactory pattern Provides for abstraction of creation ofProvides for abstraction of creation of
implementations from the tests.implementations from the tests.
Strategy patternStrategy pattern
Because FactoryFinder dynamically resolvesBecause FactoryFinder dynamically resolvesdesired factory, implementations are plugabledesired factory, implementations are plugable
-
8/6/2019 Java Jun It
47/58
Design for testing - Factories
newnew only used in Factoryonly used in Factory
Allows writing tests which can be usedAllows writing tests which can be used
across multiple implementations.across multiple implementations.
Promotes frequent testing by writingPromotes frequent testing by writing
tests which work against objects withouttests which work against objects without
requiring extensive setUprequiring extensive setUp
extra-container testing.extra-container testing.
-
8/6/2019 Java Jun It
48/58
Design for testing - Mock Objects
When your implementation requires aWhen your implementation requires a
resource which is unavailable for testingresource which is unavailable for testing
External system or database is simulated.External system or database is simulated.
Another use of Factory, the mockAnother use of Factory, the mock
implementation stubs out and returns theimplementation stubs out and returns the
anticipated results from a request.anticipated results from a request.
-
8/6/2019 Java Jun It
49/58
-
8/6/2019 Java Jun It
50/58
50
ExtensionsExtensions
-
8/6/2019 Java Jun It
51/58
JUnit Extensions
JUnitReportJUnitReport
CactusCactus
JWebUnitJWebUnit
XMLUnitXMLUnit
MockObjectMockObject
StrutsTestCaseStrutsTestCase
-
8/6/2019 Java Jun It
52/58
JUnitReport
Apache Ant extension taskApache Ant extension task
Uses XML and XSLT to generate HTMLUses XML and XSLT to generate HTML
-
8/6/2019 Java Jun It
53/58
Cactus (from Jakarta)
Simple test framework for unit testingSimple test framework for unit testingserver-side Java codeserver-side Java code
-
8/6/2019 Java Jun It
54/58
JWebUnit
Framework that facilitates creation ofFramework that facilitates creation ofacceptance tests for web applicationsacceptance tests for web applications
-
8/6/2019 Java Jun It
55/58
XMLUnit
Provides an XMLTestCase class whichProvides an XMLTestCase class whichenables assertions to be made about theenables assertions to be made about thecontent and structure of XMLcontent and structure of XML
Differences between two pieces of XMLDifferences between two pieces of XML
Validity of a piece of XMLValidity of a piece of XML
Outcome of transforming a piece of XMLOutcome of transforming a piece of XMLusing XSLTusing XSLT
Evaluation of an XPath expression on a pieceEvaluation of an XPath expression on a piece
of XMLof XML
-
8/6/2019 Java Jun It
56/58
Mock Objects
Generic unit testing framework whose goalGeneric unit testing framework whose goalis to facilitate developing unit tests in theis to facilitate developing unit tests in themock object stylemock object style
What is a Mock object?What is a Mock object?
"double agent" used to test the behaviour of other"double agent" used to test the behaviour of other
objectsobjects
Dummy object which mimics the externalDummy object which mimics the externalbehaviour of a true implementationbehaviour of a true implementation
observes how other objects interact with itsobserves how other objects interact with its
methods and compares actual behaviour withmethods and compares actual behaviour with
preset expectationspreset expectations
-
8/6/2019 Java Jun It
57/58
StrutsTestCase
Extends the JUnit TestCase class thatExtends the JUnit TestCase class that
Provides facilities for testing code basedProvides facilities for testing code basedon the Struts frameworkon the Struts framework
You can testYou can test
implementation of your Action objectsimplementation of your Action objects
mappings declarationsmappings declarations form beans declarationsform beans declarations
forwards declarationsforwards declarations
-
8/6/2019 Java Jun It
58/58
JUnit Testing FrameworkJUnit Testing Framework