The Design of JUnit Yonglei Tao. Test-First Development  An essential element in eXtreme Programming (XP)  Test is written before the code  As an executable.

Slides:



Advertisements
Similar presentations
JUnit Tutorial Hong Qing Yu Nov JUnit Tutorial The testing problems The framework of JUnit A case study JUnit tool Practices.
Advertisements

J-Unit Framework.
1 Structural Design Patterns - Neeraj Ray. 2 Structural Patterns - Overview n Adapter n Bridge n Composite n Decorator.
Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
Inheritance Inheritance Reserved word protected Reserved word super
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Design Patterns In OPM Presented by: Galia Shlezinger Instructors: Prop. Dov Dori, Dr. Iris Berger.
JUnit, Revisited 17-Apr-17.
JUnit Introduction and Advanced Features. Topics Covered  Junit Introduction  Fixtures  Test Suites  Currency Example.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
24-Jun-15 JUnit. 2 Test suites Obviously you have to test your code to get it working in the first place You can do ad hoc testing (running whatever tests.
Template Method By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
GoF Sections 2.7 – 2.9 More Fun with Lexi. Lexi Document Editor Lexi tasks discussed:  Document structure  Formatting  Embellishing the user interface.
A Unit Testing Framework: JUnit COMP 302 Software Engineering Koc University, Istanbul.
JUnitTest Infected: Programmers Love Writing Tests A little test, a little code, a little test, a little code…
More OOP Design Patterns
Client/Server Software Architectures Yonglei Tao.
Composite Design Pattern. Motivation – Dynamic Structure.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Testing in Extreme Programming
1 Testing With The JUnit Framwork Carl-Fredrik Sørensen, PhD Fellow
Unit testing Unit testing TDD with JUnit. Unit Testing Unit testing with JUnit 2 Testing concepts Unit testing Testing tools JUnit Practical use of tools.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
CSC 216/001 Lecture 4. Unit Testing  Why is it called “unit” testing?  When should tests be written?  Before the code for a class is written.  After.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
Lexi case study (Part 2) Presentation by Matt Deckard.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Chapter 38 Persistence Framework with Patterns 1CS6359 Fall 2011 John Cole.
Introduction to JUnit 3.8 SEG 3203 Winter ‘07 Prepared By Samia Niamatullah.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method Pattern.
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
EMBEDDED REAL-TIME, INC. December 8, 2015 Java Unit Mark Mosher Rochester Java Users Group.
JUnit Don Braffitt Updated: 10-Jun-2011.
JUnit A framework which provides hooks for easy testing of your Java code, as it's built Note: The examples from these slides can be found in ~kschmidt/public_html/CS265/Labs/Java/Junit.
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 11, Testing.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
S Ramakrishnan1 Systems V & V, Quality and Standards Dr Sita Ramakrishnan School CSSE Monash University.
Lecture 14 Inheritance vs Composition. Inheritance vs Interface Use inheritance when two objects share a structure or code relation Use inheritance when.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
Unit, Regression, and Behavioral Testing Based On: Unit Testing with JUnit and CUnit by Beth Kirby Dec 13, 2002 Jules.
Test a Little, Code a Little Colin Sharples IBM Global Services New Zealand Colin Sharples IBM Global Services New Zealand.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
Topic: Junit Presenters: Govindaramanujam, Sama & Jansen, Erwin.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
Command Pattern. Intent encapsulate a request as an object  can parameterize clients with different requests, queue or log requests, support undoable.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
SWE 434 SOFTWARE TESTING AND VALIDATION LAB2 – INTRODUCTION TO JUNIT 1 SWE 434 Lab.
Sections Inheritance and Abstract Classes
Software Construction Lab 10 Unit Testing with JUnit
Don Braffitt Updated: 26-Mar-2013
Unit testing Java programs Using JUnit
Inheritance and Polymorphism
Behavioral Design Patterns
Composite Design Pattern
Jim Fawcett CSE776 – Design Patterns Summer 2003
Chapter 11, Testing.
Introduction to JUnit IT323 – Software Engineering II
JUnit Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from the Eclipse 3.0 and.
Chapter 20: Software Testing - Using JUnit, and Cobertura
Presentation transcript:

The Design of JUnit Yonglei Tao

Test-First Development  An essential element in eXtreme Programming (XP)  Test is written before the code  As an executable and standalone component  Includes the input and checks the result  Can run with an automated support  Developers need to understand the interface and functionality of a component first

JUnit  A free framework for unit testing  Written by Kent Beck & Erich Gamma  Helps the developer create and run individual and groups of test cases  Allows test cases to be self-checked  Allows to run test cases when changes are made

An Example Class class Money { private int amount; private String currency; public Money(int amt, String cur) { amount= amt; currency= cur; } public int amount() { return amount; } public String currency() { return currency; } public Money add(Money m) { return new Money(amount() + m.amount(), currency()); } public boolean equals(Money other) { return amount == other.amout && currency.equals(other.currency)); }

A Test Case public class MoneyTest public void testConstructor() { Money m1= new Money(12, "USD"); Money m2= new Money(14, "USD"); assertTrue ( !m1.equals(null) ); assertEquals ( m1, m1 ); assertEquals ( m1, new Money(12, "USD") ); assertTrue ( !m1.equals(m2) ); }

More Test  Code a little, test a little, code a little, test a public void testAdd() { Money m1= new Money(12, "USD"); Money m2= new Money(14, "USD"); Money expected= new Money(26, "USD"); Money result= m1.add(m2); assertTrue ( expected.equals(result) ); }

Design Issues for JUnit  A tool for unit testing  Need to run test methods written by individual programmers  Need to work with test classes involving different test methods  Need to work with individual test cases as well as collections of test cases

The Command Pattern  Problem  Need to issue a request for an object without knowing anything about the operation being requested or the receiver of the request  Need to support undo, redo, and callback  Solution  Encapsulate a request as an object  Delegate its intended functionality to the responsible object

Command Class Hierarchy

Participating Objects nt Client

Consequences  Extend class Command for each of the commands  Let it be responsible for executing itself  Let it keep info needed for undoing/redoing  Support undoable operations as well as to queue or log users’ requests  Also callback  Adding or removing a command doesn't affect the client code

The Template Method Pattern  Problem  How to defer decision on details of an algorithm  How to allow a step in an algorithm to vary  Solution  Let a method in a superclass defines the skeleton of an algorithm with its varying and unvarying parts  Let subclasses override the varying parts in order to add their specific behavior at points of variability

An Example of the Template Method

An Example (Cont.) public class Account { public void Transaction() { A(); B(); C(); } public void A() { … } public void B() { … } public void C() { … } … } public class SavingsAccount extends Account { public void C() { … } … } public class JuniorAccount extends Account { public void A() { … } … }

Applicability  The template method should be used  To implement the invariant parts of an algorithm once and let subclasses implement behavior that can vary  When common behavior among subclasses should be factored and localized in a common class to avoid code duplication  To control subclass extension  The template method defines hook operations  Subclasses can only extend these hook operations

Use of the Pattern in C++, Java, …

Consequences  Most commonly used  An important pattern for framework and class library design  Inverted control structure  Parent class calls subclass methods  Important to denote which methods  Must overridden  Can / Can not be overridden

The Adapter Pattern  Problem  How to resolve incompatible interfaces or provide a stable interface to similar components with different interfaces  Solution  Convert the original interface of a component into another interface, through an intermediate adapter object  Also known as Wrapper

Structure

The Composite Pattern  Problem  How to allow clients to treat individual objects and compositions of objects uniformly  Solution  Organize objects into a tree structure that represents an aggregation hierarchy

Structure

GUI Windows and Elements How does the window hold and deal with the different items it has to manage?

Using the Composite Pattern

// Component implements default behavior for widgets when // Button, Menu, TextArea, and WidgetContainer override // Component methods as needed class WidgetContainer { Component[] myComponents; public void update() { if ( myComponents != null ) for ( int k = 0; k < myComponents.length(); k++ ) myComponents[k].update(); } Composite (Cont.)

Consequences  Make the client simple  Make it easy to add new kind of components and remove existing ones  Make the design general and reusable  Using the pattern when  To represent part-whole hierarchies of objects  Clients to be able to ignore the difference between compositions of objects and individual objects

Design of JUnit  Serve as a framework within which developers can write and run tests  Easy to learn and to use  Create tests that can be performed as needed  Someone other than the original author has to be able to execute the tests and interpret the results  Creating test cases is expensive and the framework has to enable reusing them

1. Getting Started  How to run test cases that are written by individual programmers?  Allow to run tests in a graphical user interface or on the command-line  Make manipulating tests easy

The Command Pattern  Separating a request for executing a command from its execution  User interaction object vs. domain object  Allowing to invoke different implementations of a command through the same interface

Pattern Implementation public abstract class TestCase implements Test { private final String fName; public TestCase(String name) { fName= name; } public abstract void run(); … }

2. Defining Tests  How to give the programmer a convenient “place” to put their test code?  Need a common structure to all tests  Set up test data, run some code against the data, check results, and then clean up the data

The Template Method Pattern  Define the skeleton of an algorithm in an operation, deferring some steps to subclasses  Let subclasses redefine certain steps of an algorithm without changing the algorithms’ structure  Allow the programmer to consider how to write the test code without worrying about how to run it  Execution of this sequence remains the same for all tests, no matter how the testing code is written

Pattern Implementation public class TestCase implements Test { private final String fName; public TestCase(String name) { fName= name; } public void run() { setUp(); runTest(); tearDown(); } protected void runTest() { } protected void setUp() { } protected void tearDown() { } }

3. Reporting Results  How to collect test results?  Need to capture what did and did not work after the test has run  Tests usually work – only need to record the failure and a highly condensed summary of the successes

The Collecting Parameter Pattern  Add a parameter to the method and pass an object that will collect the results from that method  JUnit distinguishes between failures and errors  Failures are anticipated and checked for with assertions  Errors are unanticipated problems

Pattern Implementation public void run (TestResult result) { result.startTest(this); setUp(); try { runTest(); } catch (AssertionFailedError e) {// capture failures result.addFailure(this, e); } catch (Throwable e) { // capture errors result.addError(this, e); } finally { tearDown(); } }

Class TestResult public class TestResult extends Object { protected int fRunTests; protected Vector fErrors, fFailures; public TestResult() { fRunTests= 0; fErrors = new Vector(); fFailures = new Vector(); } public synchronized vid startTest (Test test) { fRunTests++; } public synchronized void addError(Test test, Throwable t) { fErrors.addElement(new TestFailure(test, t)); } public synchronized void addFailure(Test test, Throwable t) { fFailures.addElement(new TestFailure(test, t)); } }

4. Handling Different Test Cases  How to run test cases that are implemented as different methods in the same class?  A test case class may implement many different methods, each defining one test case such as testMoneyEquals or testMoneyAdd  Need to make all test cases look the same from the point of view of the invoker of the test

The Adapter Pattern  Converting the interface of a class into another interface that clients expect  Using a class adapter requires to implement a subclass for each test case – too much burden on the tester  So use pluggable selector as default implementation of method runTest() in an anonymous adapter class

Pattern Implementation protected void runTest() throws Throwable { Method runMethod= null; try { runMethod= getClass().getMethod(fName, new Class[0]); } catch (NoSuchMethodException e) { assertTrue("Method \""+fName+"\" not found", false); } try { runMethod.invoke(this, new Class[0]); } // catch InvocationTargetException & IllegalAccessException }

5. Dealing with One and Many  How to run a single test case and report its result in a TestResult as well as run a group of test cases and report their results?  Need to support suits of suits of suits of tests

The Composite Pattern  Allowing clients treat individual objects and groups of objects uniformly

Class TestSuite public class TestSuite implements Test { private Vector fTests= new Vector(); public void run(TestResult result) { // delegates to its children for (Enumeration e= fTests.elements(); e.hasMoreElements(); ) { Test test = (Test) e.nextElement(); test.run(result); } } public void addTest(Test test) { fTests.addElement(test); } }

Summary