Unit Testing Tips and Tricks: Database Interaction Louis Thomas.

Slides:



Advertisements
Similar presentations
Testing Relational Database
Advertisements

Automating Tasks With Macros
1 Introducing Collaboration to Single User Applications A Survey and Analysis of Recent Work by Brian Cornell For Collaborative Systems Fall 2006.
Automating Tasks With Macros. 2 Design a switchboard and dialog box for a graphical user interface Database developers interact directly with Access.
Pragmatic Application Building: Step by Step Jay Sissom Principal Systems Analyst Indiana University
Java Interfaces Overview Java Interfaces: A Definition.
ASP.NET Programming with C# and SQL Server First Edition
CVSQL 2 The Design. System Overview System Components CVSQL Server –Three network interfaces –Modular data source provider framework –Decoupled SQL parsing.
Object Oriented Databases by Adam Stevenson. Object Databases Became commercially popular in mid 1990’s Became commercially popular in mid 1990’s You.
TDD,BDD and Unit Testing in Ruby
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
Pittsburgh Java User Group– Dec Java PureFaces: A JSF Framework Extension.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Design Patterns.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Prologue: The Software Process. Main Phases of Software Process 1. Requirements Analysis (answers “WHAT?”) Specifying what the application must do 2.
DEVSView: A DEVS Visualization Tool Wilson Venhola.
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
Effectively Validate Query/Report: Strategy and Tool Steven Luo Sr. System Analyst Barnes & Noble Session id:
Data File Access API : Under the Hood Simon Horwith CTO Etrilogy Ltd.
Appointment Application Belinda Whitman CS 470. Background The client is a local outpatient therapy clinic specializing in upper extremity rehabilitation.
Cerberus. Introduction Cerberus is test case generator tool. Used for automation of unit testing.
@DNNCon Don’t forget to include #DNNCon in your tweets! Effective Unit Testing for DNN James McKee Solutions Developer / Enterprise
Mark Dixon 1 09 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
Effective Test Driven Database Development Gojko Adzic
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
Refactoring An Automated Tool for the Tiger Language Leslie A Hensley
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2015 ©
Effective Test Driven Database Development Gojko Adzic
First BlueJ Day Houston, 2006 Unit Testing with BlueJ Bruce Quig Deakin University.
Selenium and Selenium on Rails. Agenda  Overview of Selenium Simple Selenium Tests Selenium IDE  Overview of Selenium on Rails  Problems with Selenium.
Chapter 38 Persistence Framework with Patterns 1CS6359 Fall 2011 John Cole.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
Refactoring & Testability. Testing in OOP programming No life in flexible methodologies and for refactoring- infected developers without SOME kind of.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming – Home and reload buttons for the webbrowser, Applets.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
DataSet Your Database student test score Database Connection Your program needs to establish a connection to the database. Click on “Add New Data Source.”
Advanced Tips And Tricks For Power Query
Unit Testing Tips and Tricks: Database Interaction Louis Thomas.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Chapter 10 Database Management. Data and Information How are data and information related? p Fig Next processing data stored on disk Step.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
MVC WITH CODEIGNITER Presented By Bhanu Priya.
(1) Test Driven Development Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
Android - SQLite Database 12/10/2015. Introduction SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with.
Advanced Object-oriented Design Patterns Creational Design Patterns.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Unit Testing Tips and Tricks: Database Interaction Louis Thomas.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.
Integrating and Extending Workflow 8 AA301 Carl Sykes Ed Heaney.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Beginning Software Craftsmanship Brendan Enrick Steve Smith
Object-Oriented Application Development Using VB.NET 1 Chapter 15 Assembling a Three-Tier Windows Application.
Copyright 2015 Varigence, Inc. Unit and Integration Testing in SSIS A New Approach Scott @varigence.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
7.5 Using Stored-Procedure and Triggers NAME MATRIC NUM GROUP Muhammad Azwan Bin Khairul Anwar CS2305A Muhammad Faiz Bin Badrol Shah CS2305B.
Get testing with tSQLt Practical examples and automation Steve Jones SQLServerCentral Red Gate Software.
By Aleksey Stukalov How to Develop Highly Customizable Off-the-Shelf Software.
Connectivity in DataFlex 19.0
Selenium and Selenium on Rails
Mocking Your Objects with Impunity
CISC124 Quiz 1 marking nears completion!
Please thank our sponsors!
Developing a Model-View-Controller Component for Joomla Part 3
Automated test.
Designing For Testability
Test-Driven Development
-Transactions in SQL -Constraints and Triggers
Zorah Fung University of Washington, Winter 2016
Plug-In Architecture Pattern
Presentation transcript:

Unit Testing Tips and Tricks: Database Interaction Louis Thomas

Overview Preaching about TDD What is a Unit Test Common Unit Testing Patterns Unit Testing Database Interactions Acceptance Tests With Databases

Are you test infected? There are two kinds of people: –People who don’t like it Can’t be done attitude –People who do like it “I think I can” attitude

Test Driven Development Is Hard Conceptually, it’s simple! (Sure, just like OO is simple…) It’s a learning process. It will be hard at first. Be creative!

I’m Guilty… I'm guilty. I am a hack. I am an "impurist". I often don't do "pure" TDD. I find TDD easier to do for some tasks than others. I do whatever I feel like. However, I like what I get with TDD, so I lean towards it Unit tests are good even if you don’t do TDD!

There Are Many Kinds Of Tests Acceptance tests, user test, integration tests, unit tests; black box, white box… All tests have merit if they can detect bugs. Tests only have value if they are run!

Unit Tests From developer's point of view. Tests the smallest amount of a system that is interesting. Often just one part of one class! Highly automated

Unit Test Rule Of Thumb If you are having trouble writing a unit test or (for those of you who aren't test infected) if it's "impossible" to write a test for your system, You are trying to test to much. Test a smaller chunk.

But How? Sometimes objects have complex behaviors, extensive state, and tight relationships. This makes tests difficult:set up is difficult and time consuming, and objects cannot be isolated. (But wait, that’s not right! Right?)

Loosening The Coupling Introduce interfaces between complex objects. Create a mock object to stand in for the complex object. Repeat as needed. (Be creative.)

Creating Interfaces If it's our object, just create an interface! if it's not our object, –create a mock that extends the object and overrides all its methods (works sometimes) –create an interface anyway and create an adapter for the foreign object Example: WallClock

public class DefaultWallClock implements WallClock { public static final WallClock INSTANCE=new DefaultWallClock(); public long getTime() { return System.currentTimeMillis(); } Interface Wrapper for normal system service public interface WallClock { long getTime(); }

Mock Objects Start out as simple as possible (throw exceptions on all methods). Add recording of incoming method calls –- ex: RecordingMockObject, Thumbprinters

Example: ReportingMockObject public class ReportingMockObject { StringBuffer m_stringBuffer=new StringBuffer(); // public String getActivityRecordAndReset() { String sActivityRecord=m_stringBuffer.toString(); m_stringBuffer=new StringBuffer(); return sActivityRecord; } // public void recordActivity(String sMessage) { m_stringBuffer.append(sMessage); }

Example: MockClientSession public class MockClientSession extends ReportingMockObject implements ClientSession { public MockClientSession() { } public void flushOutgoingBuffer() { recordActivity("fOB"); } public void setInterval(int nUpdateIntervalMilliseconds) { recordActivity("sI("+nUpdateIntervalMilliseconds+")"); } public void notifyNewOutgoingData() { recordActivity("nNOD"); } public String getClientName() { recordActivity("gCN"); return "mockClient"; } //… }

Example: MockMultiTableSessionListener public class MockMultiTableSessionListener extends ReportingMockObject implements MultiTableSession.Listener { public interface Thumbprinter { String getThumbprint(MultiTableSession.Update update); String getThumbprint(SessionState sessionState); } //################################################################ private final Thumbprinter m_thumbprinter; //… public MockMultiTableSessionListener(Thumbprinter thumbprinter) { m_thumbprinter=thumbprinter; } //… public void sessionStateNotification(SessionState sessionState) { if (true==m_bLogSessionStateNotification) { recordActivity("sSN("+m_thumbprinter.getThumbprint(sessionState)+")"); }

Mock Objects, cont’d Add facility for sending back canned responses –(ex, setNextReply, setFailOnNextRequest)

Example: WallClock public class MockWallClock implements WallClock { private long[] m_nextTimes; private int m_nNextTimeIndex; public void setNextTime(long nNextTime) { setNextTimeList(new long[] {nNextTime}); } public void setNextTimeList(long[] nextTimes) { Require.neqNull(nextTimes, "nextTimes"); m_nextTimes=nextTimes; m_nNextTimeIndex=0; } public long getTime() { Assert.neqNull(m_nextTimes, "m_nextTimes"); long nNextTime=m_nextTimes[m_nNextTimeIndex]; m_nNextTimeIndex++; if (m_nextTimes.length==m_nNextTimeIndex) { m_nextTimes=null; } return nNextTime; }

Mock Objects, cont’d Do whatever you need Often one mock object will support all tests for a given object, but can create special ones for certain tests Often, one mock object will support tests for many objects that interact with it

Mock Object Frameworks EasyMock ( jMock ( YMMV!

Object Mother (?) Sometimes you will need a complex data structure set up. Refactor mercilessly. Especially if you need canned data that is ancillary to the test, it is often worth while to factor creation out into a static method in a util class so you can use it as necessary thereafter.

Testing Accessor Problem: there are private methods you would like to test, or private members you would like to inspect for your test You could make them public, but they really are private Alternative: an inner class! TestingAccessor

Example: TestingAccessor //################################################################ // testing private WallClock m_wallClock=DefaultWallClock.instance; private IStepper m_getConStepper=DefaultStepper.instance; private IStepper m_maintStepper=DefaultStepper.instance; public class TestingAccessor { public void setWallClock(WallClock wallClock) {m_wallClock=wallClock;} public void setGetConStepper(IStepper stepper) {m_getConStepper=stepper;} public void setMaintStepper(IStepper stepper) {m_maintStepper=stepper;} public void setNextOverdueConnectionCheck(long tsNextOverdueConnectionCheck) {m_tsNextOverdueConnectionCheck=tsNextOverdueConnectionCheck;} public int getAllConnectionsSize() {return m_allConnections.size();} public int getUnusedConnectionsSize() {return m_unusedConnections.size();} public int getTotalConnections() {return m_nTotalConnections;} public void cacheMaintenaceThread() {DBConnectionPool.this.cacheMaintenaceThread();} public void doNotifyAll() {synchronized (m_oStateLock) {m_oStateLock.notifyAll();}} } public TestingAccessor getTestingAccessor() { return new TestingAccessor(); }

Testing Database Interactions You should be thankful! All the database classes are interfaces already! Create mocks and away you go Insert / update / delete – easy

Testing Database Interactions, Cont’d Read – trickier Can use hard coded expectations Mocks will act as factories: statements return record sets – load your mock statement with the mock record set to return. – load your mock connection with the mock statement to return. Can start out with mocks with hard coded returns, but will probably refactor into more general objects. Ex: Simulated Database Framework

Acceptance Tests With Databases An acceptance test: Want to test the "whole" app. Good for testing that the database really likes the SQL we hardcoded in the unit tests, and really responds the way we expect

Acceptance Tests With Databases, Cont’d Big question is, how can we automate? I built up a toolkit as I went. –BulkLoadData: reads CSV files and loads data into DB (use Excel to edit) –ExecuteSqlScript: processes a text file of SQL commands. Used to create tables, etc. –ExecuteDatabaseSetupScript: allows me to write little scripts Knows about 4 commands, including BulkLoadData and ExecuteSqlScript –TestResource framework

Acceptance Tests With Databases, Cont’d Big question is, how can we automate? I built up a toolkit as I went. –TestResource framework I can define test resources my test needs, setup/teardown methods, and dependencies. Resources will set themselves up from any initial state (ex, delete all rows in table and reload) Now, the acceptance test can just declare all the resources it needs, and framework will set them up. Just needs to mark which resources it dirties, so they can be reset for subsequent tests.

Summary Preaching about TDD What is a Unit Test Common Unit Testing Patterns Unit Testing Database Interactions Acceptance Tests With Databases Questions / demos!