Test Isolation and Mocking Technion – Institute of Technology 236700 Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2015 ©

Slides:



Advertisements
Similar presentations
CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann.
Advertisements

Identity and Equality Based on material by Michael Ernst, University of Washington.
Written by: Dr. JJ Shepherd
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Excel What’s so great about PivotTable reports?. Course contents Overview: More data than you can handle? Lesson 1: Make your data work for you Lesson.
From Module Breakdown to Interface Specifications Completing the architectural design of Map Schematizer.
UML exam advice. Minimal, yet sufficient UML course 80% of modeling can be done with 20% of the UML. Which 20% was that again? We’re supposed to be “Use.
Unit Testing Tips and Tricks: Database Interaction Louis Thomas.
Mock Objects. What are Mock Objects  Any dummy object that stands in for a real object that is not available, or is difficult to use in a test case 
Programmer Testing Testing all things Java using JUnit and extensions.
Struts 2.0 an Overview ( )
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Technion – Institute of Technology Author: Gal Lalouche ©
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2015 © 1.
E-Learning Material Web Application Design 2. Web Application Design Use cases Guidelines Exceptions Interaction Sequence diagrams Finding objects.
CSC 213 – Large Scale Programming. Why Do We Test?
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
Capture-Replay Mocks Scandinavian Developer Conference 4 th April 2011 Geoff Bache.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Junit At the forefront of Test Driven Development.
@DNNCon Don’t forget to include #DNNCon in your tweets! Effective Unit Testing for DNN James McKee Solutions Developer / Enterprise
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
Best Practices. Contents Bad Practices Good Practices.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Mock Objects in Action Paulo Caroli & Sudhindra Rao Agile 2009 © ThoughtWorks 2008.
Documentation. Your documentation must fit the needs of your audience. It’s always better to say one thing that is useful, as opposed to many things that.
Refactoring & Testability. Testing in OOP programming No life in flexible methodologies and for refactoring- infected developers without SOME kind of.
TOS / TIS Code Architecture Copyright © 2008 Talend. All rights reserved.
Mock objects.
1 CS161 Introduction to Computer Science Topic #9.
Software testing techniques Software testing techniques Software Testability Presentation on the seminar Kaunas University of Technology.
Dependency Injection Frameworks Technion – Institute of Technology Author: Assaf Israel - Technion 2013 ©
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 Events, Listeners, and Callbacks (slides by Mike Ernst and David Notkin) 1.
DFS DBufferCache DBuffer VirtualDisk startRequest(dbuf, r/w) ioComplete() blockID = getBlockID() buf[] = getBuffer() read(), write() startFetch(), startPush()
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Written by: Dr. JJ Shepherd
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
CS 350 – Software Design The Adapter Pattern – Chapter 7 Gang of Four Definition: Convert the interface of a class into another interface that the client.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
Lecture IX: Testing Web Services with Mocking CS 4593 Cloud-Oriented Big Data and Software Engineering.
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
Beginning Software Craftsmanship Brendan Enrick Steve Smith
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Caching: An Optimization Aspect. Class Diagram for Base Item +name : String +check() : int Simple +weight : int +check() : int Container +capacity : int.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
Testing Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
Unit testing Why test your code when your code can test it for you?
Reference: Object Oriented Design and Programming (Horstmann)
Solving systems of equations
Mocking Tool for easier unit testing
Comments on the “Three Piles” Problem
Test Isolation and Mocking
Designing For Testability
C++ coding standard suggestion… Separate reasoning from action, in every block. Hi, this talk is to suggest a rule (or guideline) to simplify C++ code.
Week 3 - Friday CS221.
Building Rock-Solid Software
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
Design by Contract Fall 2016 Version.
Programming in Java Assertion.
Testing a persistence layer
Developing and testing enterprise Java applications
Designing For Testability
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2015 ©

Unit Testing: Isolation Initializing collaborators may include a lot of boiler plate There may be bugs in the dependencies Dependencies may not even be written yet! I/O operations (databases/files/sockets) in test subjects may slow down tests and be hard to configure Using concrete classes couples our tests with those classes 2 Author: Gal Lalouche - Technion 2015 ©

Unit Testing: Isolation Solution: Replace dependencies with mock objects Very simple dependencies that are 100% bug free Although it is possible for bugs to appear in the mock objects configurations Very easy to control their behavior Very easy to assert their use by the tested class Warehouse DataBase db ==================== void process(Order o) SQL DB db.getProduct(o.productID); Production HashTable db.getProduct(o.productID); Testing Warehouse DataBase db ==================== void process(Order o) 3 Author: Gal Lalouche - Technion 2015 ©

Unit Testing: Isolation Once again, code testability improves its design! Isolation forces the code to be: Modular Decoupled from its dependencies More coherent Author: Gal Lalouche - Technion 2015 © 4 PizzaOrder CreditCard Processor PizzaOrder Mock Processor PizzaOrder Paypal Processor charge() Testing Today Tomorrow

Unit Testing: Mockito Problem: Writing mock objects can be a pain A great deal of time is wasted writing an object that is only used for testing Configuration can be tricky Validation is also problematic Case Study – Shopping cart Shoppers can add/remove items from the shopping cart Each item is a complex object with many attributes The shopping cart is initialized with a ShoppingSuggestions which offer other purchases based on the shopping cart content Author: Gal Lalouche - Technion 2015 © 5

Case study – Shopping cart Author: Gal Lalouche - Technion 2015 © 6

Case study – Shopping cart We want to test the ShoppingCart class The ShoppingSuggestions is responsible for displaying product suggestions based on the shopping cart contents Author: Gal Lalouche - Technion 2015 © 7 public class ShoppingCart { private Map items = new HashMap<>(); private ShoppingSuggestions suggestions; public ShoppingCart(ShoppingSuggestions suggestions) { this.suggestions = suggestions; } … }

Case study – Shopping cart We would like to test the following methods Author: Gal Lalouche - Technion 2015 © 8 public void addItem(Item item) { int amount = 1; if (items.containsKey(item)) { amount = items.get(item) + 1; } items.put(item, amount); suggestions.displaySuggestionFor(item); } public void removeItem(Item item) { if (!items.containsKey(item)) return; int amount = items.get(item); if (amount == 0) { items.remove(item); suggestions.removeSuggestionFor(item); return; } items.put(item, amount - 1); } Bug: Should be 1

Testing our Shopping cart – Take 1 We want to isolate the subject class and replace arguments and dependencies with controlled objects (Mocks) We will start with a naïve mock of ShoppingSuggestions We will soon see this is not enough Author: Gal Lalouche - Technion 2015 © 9 class FakeShoppingSuggestions implements ShoppingSuggestions { public boolean invoked = public void removeSuggestionFor(Item item) { invoked = true; public void displaySuggestionFor(Item item) { invoked = true; } }

Testing our Shopping cart – Take 1 Let’s look at our first test: Author: Gal Lalouche - Technion 2015 © public void updateSuggestionWhenAddingItem() { FakeShoppingSuggestions ss = new FakeShoppingSuggestions(); Item someItem = new Item(1,3000,"laptop","Lenovo”, Category.Computers ); ShoppingCart cart = new ShoppingCart(ss); cart.addItem(someItem); assertTrue(ss.invoked); } We would like to use the ShoppingSuggestions interface, so to be sure we haven’t introduced bugs in the test… but we can’t because of the last assert. We don’t really care about these details This test doesn’t check how many times each method was invoked, and is susceptible to bugs in the mock object.

Testing our Shopping cart – Take 1 Our second test is even more problematic In order to deal with some of these problems we must write smarter (and possibly buggier) mock objects. Author: Gal Lalouche - Technion 2015 © public void removeSuggestionWhenRemovingLastItem() { FakeShoppingSuggestions ss = new FakeShoppingSuggestions(); Item someItem = new Item(1,3000,"laptop","Lenovo", Category.Computers ); ShoppingCart cart = new ShoppingCart(ss); cart.addItem(someItem); ss.invoked = false; cart.removeItem(someItem); assertTrue(ss.invoked); } We must update our mocking object throughout the test. What happens if we forget?

Testing our Shopping cart – Mockito We will use a Mocking Framework (Mockito) to create our mock objects, define their behavior and verify the results. Author: Gal Lalouche - Technion 2015 © public void updateSuggestionWhenAddingItem() { ShoppingSuggestions ss = Mockito.mock(ShoppingSuggestions.class); Item someItem = Mockito.mock(Item.class); ShoppingCart cart = new ShoppingCart(ss); cart.addItem(someItem); Mockito.verify(ss, Mockito.only()).displaySuggestionFor(someItem); } We simply ask for a ShoppingSuggestions and Item mocks We can verify that the displaySuggestionFor() method will be called exactly once with the someItem argument.

Testing our Shopping cart – Take 2 Let’s look at our second test: Author: Gal Lalouche - Technion 2015 © public void removeSuggestionWhenRemovingLastItem() { ShoppingSuggestions ss = Mockito.mock(ShoppingSuggestions.class); Item someItem = Mockito.mock(Item.class); ShoppingCart cart = new ShoppingCart(ss); cart.addItem(someItem); Mockito.verify(ss, Mockito.only()).displaySuggestionFor(someItem); cart.removeItem(someItem); Mockito.verify(ss, Mockito.only()).removeSuggestionFor(someItem); } Wanted but not invoked: suggestions.removeSuggestionFor( Mock for Item, hashCode: ); -> at ShoppingCartTestWithMockito.testRemoveItem(ShoppingCartTestWithMockito.java:29)

Testing our Shopping cart – Take 2 Using a Mocking Framework we do not need to write a complete class to define the mock behavior: Author: Gal Lalouche - Technion 2015 © public void testTotalAmount() { ShoppingSuggestions ss = Mockito.mock(ShoppingSuggestions.class); Item someItem = Mockito.mock(Item.class); ShoppingCart cart = new ShoppingCart(ss); Mockito.when(someItem.getPrice()).thenReturn(70); Mockito.when(someItem.getShippingCosts()).thenReturn(6); cart.addItem(someItem); Assert.assertEquals(76, cart.total()); } We only define what we’re interested in. We can also tell the mock to throw an exception.