Testing with Mock Objects



Similar documents
Plugin JUnit. Contents. Mikaël Marche. November 18, 2005

JUnit IN ACTION. Vincent Massol with Ted Husted MANNING

Java course - IAG0040. Unit testing & Agile Software Development

CSE 326: Data Structures. Java Generics & JUnit. Section notes, 4/10/08 slides by Hal Perkins

Unit Testing. and. JUnit

TESTING WITH JUNIT. Lab 3 : Testing

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Approach of Unit testing with the help of JUnit

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

Tutorial for Creating Resources in Java - Client

Unit Testing JUnit and Clover

The junit Unit Tes(ng Tool for Java

Tools for Integration Testing

Tutorial IV: Unit Test

Testing Tools and Techniques

Tutorial for Spring DAO with JDBC

Settlers of Catan Phase 1

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

JUnit. Introduction to Unit Testing in Java

JUnit Automated Software Testing Framework. Jeff Offutt. SWE 437 George Mason University Thanks in part to Aynur Abdurazik. What is JUnit?

APPENDIX A: MOCKITO UNIT TESTING TUTORIAL

Unit testing with JUnit and CPPUnit. Krzysztof Pietroszek

Unit Testing and JUnit

Software Development with UML and Java 2 SDJ I2, Spring 2010

Sophos Mobile Control Network Access Control interface guide

Using JUnit in SAP NetWeaver Developer Studio

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

UltraQuest Cloud Server. White Paper Version 1.0

Development Environment and Tools for Java. Brian Hughes IBM

Assignment 3 Version 2.0 Reactive NoSQL Due April 13

Testability of Dependency injection

Pipeline Orchestration for Test Automation using Extended Buildbot Architecture

UNIT TESTING. Written by Patrick Kua Oracle Australian Development Centre Oracle Corporation

Tutorial 7 Unit Test and Web service deployment

A Practical Guide to Test Case Types in Java

Performance Testing from User Perspective through Front End Software Testing Conference, 2013

Practice Fusion API Client Installation Guide for Windows

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor

Verify Needed Root Certificates Exist in Java Trust Store for Datawire JavaAPI

DocuSign for SharePoint

Mercury Users Guide Version 1.3 February 14, 2006

Tes$ng Hadoop Applica$ons. Tom Wheeler

Module 4: File Reading. Module 5: Database connection

Test Driven Development

2. Follow the installation directions and install the server on ccc

Domain Specific Languages for Selenium tests

Automated Web Testing with Selenium

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

Overview of Web Services API

Unit Testing & JUnit

Team 23 Design Document. Customer Loyalty Program for Small Businesses

Test-Driven Development

JUnit - A Whole Lot of Testing Going On

Alteryx Predictive Analytics for Oracle R

Upgrading User-ID. Tech Note PAN-OS , Palo Alto Networks, Inc.

Going Interactive: Combining Ad-Hoc and Regression Testing

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Extreme Programming and Embedded Software Development

SysPatrol - Server Security Monitor

Software Quality Exercise 2

Appium mobile test automation

Grails 1.1. Web Application. Development. Reclaiming Productivity for Faster. Java Web Development. Jon Dickinson PUBLISHING J MUMBAI BIRMINGHAM

Unit-testing with JML

SAIP 2012 Performance Engineering

Java Unit testing with JUnit 4.x in Eclipse

Educational Collaborative Develops Big Data Solution with MongoDB

Working with Structured Data in Microsoft Office SharePoint Server 2007 (Part1): Configuring Single Sign On Service and Database

Testing the Composability of Plug-and-Play Components

Rapid Application Development. and Application Generation Tools. Walter Knesel

MarkLogic Server. Reference Application Architecture Guide. MarkLogic 8 February, Copyright 2015 MarkLogic Corporation. All rights reserved.

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

Amazon Glacier. Developer Guide API Version

Secure File Transfer Help Guide

ILMT Central Team. Performance tuning. IBM License Metric Tool 9.0 Questions & Answers IBM Corporation

Introduction to HP ArcSight ESM Web Services APIs

Testing, Debugging, and Verification

Unit and Functional Testing for the ios Platform. Christopher M. Judd

General principles and architecture of Adlib and Adlib API. Petra Otten Manager Customer Support

Lab work Software Testing

Table of Contents. LESSON: The JUnit Test Tool...1. Subjects...2. Testing What JUnit Provides...4. JUnit Concepts...5

Taxi Service Design Description

UI Performance Monitoring

IP phone services setup

Capabilities of a Java Test Execution Framework by Erick Griffin

PROFESSIONAL. Node.js BUILDING JAVASCRIPT-BASED SCALABLE SOFTWARE. Pedro Teixeira WILEY. John Wiley & Sons, Inc.

Pragmatic Unit Testing

Transcription:

A mock object is an object created to stand in for an object that your code will be collaborating with. Your code can call methods on the mock object, which will deliver results as set up by your tests. In other words, in a fine-grained unit test, you want to test only one thing. To do this, you can create mock objects for all of the other things that your method/object under test needs to complete its job.

Example Suppose we have a system that allows us to transfer money from one bank account to another. We want to test just the transfer method which resides in the AccountService class and uses an AccountManager to retrieve Accounts, all of which are stored in a database. AccountService Account AccountManager DB

//from JUnit in Action public class AccountService { private AccountManager accountmanager; public void setaccountmanager(accountmanager manager) { this.accountmanager = manager; public void transfer(string senderid, String beneficiaryid, long amount) { Account sender = this.accountmanager.findaccountforuser(senderid); Account beneficiary = this.accountmanager.findaccountforuser(beneficiaryid); sender.debit(amount); beneficiary.credit(amount); this.accountmanager.updateaccount(sender); this.accountmanager.updateaccount(beneficiary);

//from JUnit in Action public interface AccountManager{ Account findaccountforuser(string userid); void updateaccount(account account); We assume there is a class that implements the AccountManager interface and interacts with the database. We want to create a mock object in place of the real thing. Account is simple enough that we will use the actual class.

//from JUnit in Action import java.util.hashtable; public class MockAccountManager implements AccountManager { private Hashtable accounts = new Hashtable(); public void addaccount(string userid, Account account) { this.accounts.put(userid, account); public Account findaccountforuser(string userid) { return (Account) this.accounts.get(userid); public void updateaccount(account account) { // do nothing

//from JUnit in Action public class TestAccountService extends TestCase{ public void testtransferok() { MockAccountManager mockaccountmanager = new MockAccountManager(); Account senderaccount = new Account("1", 200); Account beneficiaryaccount = new Account("2", 100); mockaccountmanager.addaccount("1", senderaccount); mockaccountmanager.addaccount("2", beneficiaryaccount); AccountService accountservice = new AccountService(); accountservice.setaccountmanager(mockaccountmanager); accountservice.transfer("1", "2", 50); assertequals(150, senderaccount.getbalance()); assertequals(150, beneficiaryaccount.getbalance());

Tests use production code. Sometimes a test pushes you to change your production code to make it more testable, usually making it more flexible and less coupled to other objects. Mock Objects are notorious for improving your production code.

EasyMock EasyMock is a third-party library for simplifying creating mock objects Download EasyMock1.2 for Java1.3 from www.easymock.org EasyMock 2.0 depends on Java 1.5 Extract download Add easymock.jar to project

Testing Bank with EasyMock package bank; import java.util.collection; import org.easymock.mockcontrol; import junit.framework.testcase; public class TestBank extends TestCase { private Bank b; private MockControl control; private Collection mock; protected void setup() { control = MockControl.createControl(Collection.class); mock = (Collection) control.getmock(); b = new Bank(mock); public void testnumaccounts() { mock.size(); control.setreturnvalue(7); control.replay(); assertequals(b.getnumaccounts(),7); control.verify(); Import MockControl Collection is mock. We want to test Bank, not Collection Recording what we we expect: size() should be called, returning 7 Turn on mock with replay() Check expectations with verify()

Testing getlargest() with package bank; import java.util.sortedset; EasyMock import org.easymock.mockcontrol; import junit.framework.testcase; public class TestBank extends TestCase { public void testgetlargest() { control = MockControl.createControl(SortedSet.class); SortedSet mock = (SortedSet) control.getmock(); b = new Bank(mock); mock.last(); try{ last() should be called on mock control.setreturnvalue(new Account("Richie Rich",77777,99999.99)); control.replay(); assertequals(b.getlargest().getbalance(),99999.99,.01); catch (Exception e) { fail("testgetlargest should not throw exception"); control.verify();

When to use Mock Objects When the real object has non-deterministic behavior (e.g. a db that is always changing) When the real object is difficult to set up When the real object has behavior that is hard to cause (such as a network error) When the real object is slow When the real object has (or is) a UI When the test needs to query the object, but the queries are not available in the real object When the real object does not yet exist * from http://c2.com/cgi/wiki?mockobject