SlideShare a Scribd company logo
SCAFFOLDING WITH JMOCK
Software Engineering Class
Valerio Maggio, Ph.D.
valerio.maggio@unina.it
Prof.Adriano Peron
June 6, 2013
Scaffolding with JMock
EXERCISE 1
Calculator
A BIGTHANKYOU GOESTO..
Luciano Conte
Vittorio Parrella
Marco Zeuli
CALCULATOR CLASS
• Requirements:
• Input numbers cannot have
more than 5 digits;
• The calculator can remember
a given (unique) number;
• Only non-negative numbers
are allowed.
• In case of negative numbers,
an exception is thrown!
Calculator
+ add (double augend, double addend): double
+ subtract (double minuend, double subtrahend): double
+ multiply (double multiplicand, double multiplier): double
+ divide (double dividend, double divisor): double
+ addToMemory(double number): void
+ recallNumber(): double
- memory: double
+ MAX_DIGITS_LEN: int = 5 <<final>> <<static>>
EXERCISE 1I
Stack
STACK: LIFO QUEUE
Stack
<<constructor>>
+ Stack(capacity: int)
+ pop(): Process
+ push(Process p): void
Process
+ getName():String
+ setName(String n): void
+getPid(): Integer
+ setPid(Integer pid): void
+getPriority():Integer
+setPriority(Integer p): void
- name: String
- pid: Integer
- priority: Integer (default=-1)
*1
_list
BRIEF RECAP OF:
“PROGRAMMING CLASS”
FIFO QUEUE
enqueue()
BRIEF RECAP OF:
“PROGRAMMING CLASS”
FIFO QUEUE
enqueue()
BRIEF RECAP OF:
“PROGRAMMING CLASS”
FIFO QUEUE
enqueue() dequeue()
BRIEF RECAP OF:
“PROGRAMMING CLASS”
FIFO QUEUE
enqueue() dequeue()
BRIEF RECAP OF:
“PROGRAMMING CLASS”
enqueue() dequeue()
LIFO QUEUE
BRIEF RECAP OF:
“PROGRAMMING CLASS”
enqueue() dequeue()
LIFO QUEUE
BRIEF RECAP OF:
“PROGRAMMING CLASS”
enqueue() dequeue()
LIFO QUEUE
BRIEF RECAP OF:
“PROGRAMMING CLASS”
enqueue() dequeue()
LIFO QUEUE
+ enqueue(Process p):void
+ dequeue():Process
<<abstract>>
Queue
*1
_list
Process
FIFOQueue LIFOQueue PriorityQueue
+ addProcess(Process p, Queue q):void
+ schedule(Queue q):Process
Scheduler
1 *
_queues
Q: How would you test Scheduler? Remember: Unit tests run in isolation!
TEST SCAFFOLDING
INTEGRATIONTESTING
INTEGRATIONTESTING
INTEGRATIONTESTING
PROBLEM
• Integrate multiple components implies to decide in which
order classes and subsystems should be integrated and tested
• CITO Problem
• Class IntegrationTesting Order Problem
• Solution:
• Topological sort of dependency graph
INTEGRATIONTESTING
EXAMPLE
ClassA ClassB
ClassC Subsystem
ClassA ClassB
ClassC Subsystem
INTEGRATIONTESTING
EXAMPLE
ClassA ClassB
ClassC Subsystem
ClassA ClassB
ClassC Subsystem
TESTING IN ISOLATION
Testing in Isolation benefits!
TESTING IN ISOLATION
Test code that have not been written
Testing in Isolation benefits!
TESTING IN ISOLATION
Test only a single method (behavior) without
side effects from other objects
Test code that have not been written
Testing in Isolation benefits!
SCHEDULER EXAMPLE
+ enqueue(Process p):void
+ dequeue():Process
<<abstract>>
Queue
*1
_list
Process
FIFOQueue LIFOQueue PriorityQueue
+ addProcess(Process p, Queue q):void
+ schedule(Queue q):Process
Scheduler
1 *
_queues
s:Schedulerclient
addProcess(P, Q)
q:Queue
enqueue(P)
SCHEDULER@addProcess
SOLUTION WITH STUBS
@Marco Zeuli
KEY IDEAS
• Wrap all the details of Code
• (sort of) Simulation
• Mocks do not provide our own implementation of the
components we'd like to swap in
• Main Difference:
• Mocks test behavior and interactions between components
• Stubs replace heavyweight process that are not relevant to
a particular test with simple implementations
MOCK OBJECTS
• Powerful way to implement BehaviorVerification
• while avoidingTest Code Duplication between similar tests.
• It works by delegating the job of verifying the indirect outputs
of the SUT
• Important Note: Design for Mockability
• Dependency Injection Pattern
NAMING CONFUSION
• Unfortunately, while two components are quite distinct, they're
used interchangeably.
• Example: spring-mock package
• If we were to be stricter in terms of naming, stub objects
defined previously are test doubles
• Test Doubles, Stubs, Mocks, Fake Objects… how could we
work it out ?
TEST DOUBLE PATTERN
• Q: How can we verify logic independently when code it depends on
is unusable?
• Q1: How we can avoid slow tests ?
• A:We replace a component on which the SUT depends with a “test-
specific equivalent.”
TEST STUB PATTERN
• Q: How can we verify logic independently when it depends
on indirect inputs from other software components ?
• A:We replace a real objects with a test-specific object that
feeds the desired inputs into the SUT
MOCKS OBJECTS
• Q: How can we implement BehaviorVerification for indirect
outputs of the SUT ?
• A:We replace an object on which the SUT depends on with
a test-specific object that verifies it is being used correctly by
the SUT.
MOCK LIBRARIES
• Two main design philosophy:
• DSL Libraries
• Record/Replay Models Libraries
Record Replay Frameworks: First
train mocks and then verify expectations
DSL Frameworks:
•Domain Specific Languages
•Specifications embedded in “Java” Code
MOCK LIBRARIES
• Two main design philosophy:
• DSL Libraries
• Record/Replay Models Libraries
Record Replay Frameworks: First
train mocks and then verify expectations
DSL Frameworks:
•Domain Specific Languages
•Specifications embedded in “Java” Code
SOLUTION WITH JMOCK
JMOCK MAIN FEATURES
JMOCK FEATURES (INTRO)
• JMock previous versions required subclassing
• Not so smart in testing
• Now directly integrated with Junit4
• JMock tests requires more typing
• JMock API is extensible
JMOCK FEATURES
• JMock syntax relies heavily on chained method calls
• Sometimes difficult to decipher and to debug
• Common Patterns:
invocation-count(mockobject).method(arguments);
inSequence(sequence-name);
when(state-machine.is(state-name));
will(action);
then(state-machine.is(new-state name));
1.TEST FIXTURE
• Mockery represents the context
• JUnitRuleMockery replaces the @RunWith(JMock.class)
annotation
• JUnit4Mockery reports expectation failures as JUnit4 test failures
2. CREATE MOCK OBJECTS
• References (fields andVars) have to be final
• Accessible from Anonymous Expectations
3.TESTS WITH EXPECTATIONS
• A test sets up it expectations in one or more expectation
blocks
• An expectation block can contain any number of
expectations
• Expectation blocks can be interleaved with calls to the
code under test.
3.TESTS WITH EXPECTATIONS
• Expectations have the following structure:
invocation-count(mockobject).method(arguments);
inSequence(sequence-name);
when(state-machine.is(state-name));
will(action);
then(state-machine.is(new-state name));
WHAT ARETHOSE DOUBLE BRACES?
• Anonymous subclass of Expectations
• Baroque structure to provide a scope for setting expectations
• Collection of expectation components
• Is an example of Builder Pattern
• Improves code completion
COOKBOOK: EXPECT A
SEQUENCE OF INVOCATIONS
Expect that a sequence of method calls has
been executed in the right order
@Marco Zeuli
@Marco Zeuli
EXPECTASEQUENCE
OFINVOCATIONS
EXERCISE III
Roman Calculator
A SIMPLE EXAMPLE:
THE ROMAN CALCULATOR
Everyone always uses the same one, which is a Roman
Numerals, but I’m going to give it a little twist, which is that I’ll try
and use a Roman Numeral calculator - not a Roman Numeral
converter [...]
Source: https://github.com/hjwp/tdd-roman-numeral-calculator
PYTHON
• Language for geeks
• Multi-paradigm
• StrongTyped
• DynamicTyped
• Language for “serious” guys
• Object Oriented Language
• StrongTyped
• StaticTyped
JAVAvs
DUCKTYPING
•Walks like a duck?
•Quacks like a duck?
•Yes, It’s a duck!
def half (n):
return n/2.0
Q: What is the type of
the variable n
ISTHERE SOMEONETHAT
(REALLY) USES PYTHON?
• IBM, Google, Microsoft, Sun, HP,
NASA, Industrial Light and Magic
• Google it!
• site:microsoft.com python
• You’ll get more than 9k hits
CONTACTS
MAIL:
valerio.maggio@unina.it
http://wpage.unina.it/valerio.maggio
REFERENCES (1)
Growing Object-Oriented
Software, Guided ByTests
Freeman and Pryce,Addison
Wesley 2010
JMock Project WebSite
(http://jmock.org)
REFERENCES (II)
xUnitTest Patterns:
RefactoringTest Code
Meszaros G., Pearson
Education 2007

More Related Content

PPT
Stopping the Rot - Putting Legacy C++ Under Test
PPTX
TDD and the Legacy Code Black Hole
PDF
Golang dot-testing-lite
PPTX
Applying TDD to Legacy Code
PPT
20111018 boost and gtest
PDF
C++ Unit Test with Google Testing Framework
PDF
Modern Python Testing
PPT
Stopping the Rot - Putting Legacy C++ Under Test
TDD and the Legacy Code Black Hole
Golang dot-testing-lite
Applying TDD to Legacy Code
20111018 boost and gtest
C++ Unit Test with Google Testing Framework
Modern Python Testing

What's hot (19)

ODP
Python unit testing
PPT
Google mock for dummies
PDF
TDD CrashCourse Part3: TDD Techniques
PDF
關於測試,我說的其實是......
PPTX
Dimensional performance benchmarking of SQL
ODP
Klee introduction
PDF
Debug - MITX60012016-V005100
DOCX
Test driven development and unit testing with examples in C++
PPTX
Symbolic Execution And KLEE
KEY
iOS Unit Testing
PPT
Presentation_C++UnitTest
PPTX
SoCal Code Camp 2015: An introduction to Java 8
PDF
Beyond PITS, Functional Principles for Software Architecture
PPTX
Java 8 new features
PPT
Python testing
PDF
Java8 features
PPTX
How to Profit from Static Analysis
PPTX
Tdd & unit test
PPT
Core java day4
Python unit testing
Google mock for dummies
TDD CrashCourse Part3: TDD Techniques
關於測試,我說的其實是......
Dimensional performance benchmarking of SQL
Klee introduction
Debug - MITX60012016-V005100
Test driven development and unit testing with examples in C++
Symbolic Execution And KLEE
iOS Unit Testing
Presentation_C++UnitTest
SoCal Code Camp 2015: An introduction to Java 8
Beyond PITS, Functional Principles for Software Architecture
Java 8 new features
Python testing
Java8 features
How to Profit from Static Analysis
Tdd & unit test
Core java day4
Ad

Viewers also liked (6)

PDF
Test Driven Development
PDF
Unit testing and scaffolding
PDF
Software testing methods, levels and types
PPT
Manual testing ppt
PPT
Software Testing Fundamentals
PPTX
Software testing ppt
Test Driven Development
Unit testing and scaffolding
Software testing methods, levels and types
Manual testing ppt
Software Testing Fundamentals
Software testing ppt
Ad

Similar to Scaffolding with JMock (20)

PPTX
Unit Testing
PDF
How and what to unit test
PDF
CBDW2014 - Behavior Driven Development with TestBox
PPTX
Unit Testing Full@
PPTX
Grails Spock Testing
PDF
Codemotion 2015 spock_workshop
PDF
Database development unit test with tSQLt
PPTX
Qt test framework
 
PPTX
AOP on Android
PPTX
VT.NET 20160411: An Intro to Test Driven Development (TDD)
PDF
System verilog important
PDF
Devday2016 real unittestingwithmockframework-phatvu
PPT
Ch11lect1 ud
PPTX
OpenDaylight Developer Experience 2.0
PDF
Building a Complex, Real-Time Data Management Application
PPTX
Unit tests and TDD
PDF
Software Engineering - RS3
PDF
Test box bdd
PDF
Unit Testing in R with Testthat - HRUG
PPTX
presentation des google test dans un contexte de tdd
Unit Testing
How and what to unit test
CBDW2014 - Behavior Driven Development with TestBox
Unit Testing Full@
Grails Spock Testing
Codemotion 2015 spock_workshop
Database development unit test with tSQLt
Qt test framework
 
AOP on Android
VT.NET 20160411: An Intro to Test Driven Development (TDD)
System verilog important
Devday2016 real unittestingwithmockframework-phatvu
Ch11lect1 ud
OpenDaylight Developer Experience 2.0
Building a Complex, Real-Time Data Management Application
Unit tests and TDD
Software Engineering - RS3
Test box bdd
Unit Testing in R with Testthat - HRUG
presentation des google test dans un contexte de tdd

More from Valerio Maggio (12)

PDF
Unsupervised Machine Learning for clone detection
PDF
Improving Software Maintenance using Unsupervised Machine Learning techniques
PDF
Number Crunching in Python
PDF
Clone detection in Python
PDF
Machine Learning for Software Maintainability
PDF
LINSEN an efficient approach to split identifiers and expand abbreviations
PDF
A Tree Kernel based approach for clone detection
PDF
Refactoring: Improve the design of existing code
PDF
Junit in action
PDF
Unit testing with Junit
PDF
Design patterns and Refactoring
PDF
Web frameworks
Unsupervised Machine Learning for clone detection
Improving Software Maintenance using Unsupervised Machine Learning techniques
Number Crunching in Python
Clone detection in Python
Machine Learning for Software Maintainability
LINSEN an efficient approach to split identifiers and expand abbreviations
A Tree Kernel based approach for clone detection
Refactoring: Improve the design of existing code
Junit in action
Unit testing with Junit
Design patterns and Refactoring
Web frameworks

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Programs and apps: productivity, graphics, security and other tools
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Machine learning based COVID-19 study performance prediction
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Programs and apps: productivity, graphics, security and other tools
The AUB Centre for AI in Media Proposal.docx
Per capita expenditure prediction using model stacking based on satellite ima...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Advanced methodologies resolving dimensionality complications for autism neur...
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Digital-Transformation-Roadmap-for-Companies.pptx
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
Chapter 3 Spatial Domain Image Processing.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
sap open course for s4hana steps from ECC to s4
Machine learning based COVID-19 study performance prediction
MIND Revenue Release Quarter 2 2025 Press Release
Building Integrated photovoltaic BIPV_UPV.pdf

Scaffolding with JMock