Pattern your way
to automated regression testing
Tutorial Details:
Pattern your way to automated regression testing
Pattern your way to automated regression testing
By: By Kevin Pauli
Implement popular design patterns to overcome unit-testing hurdles
e have all heard the mantra: test, test, test. Unit test all mission-critical business logic. If possible, write the unit tests before you write the code. Test everything you can, and test it often.
Frequent testing is one of the extreme programming fundamentals, a set of practices growing in popularity because it provides a sound approach to dealing with the inevitable complexity and change of today's programming projects. But the simple mantra to test is much easier said than done, and far more often preached than practiced. Deadlines approach, managers loom, and important testing gets postponed yet again.
In the past, a major obstacle to adequate unit testing was the inherent startup costs to design and implement an acceptable unit-testing framework. Without a framework, unit tests were haphazardly implemented, and very difficult to aggregate into test suites that ran with the click of a button. Fortunately, Erich Gamma and Kent Beck have implemented Beck's Smalltalk unit testing framework in Java, called JUnit . This excellent framework, already the de facto standard for implementing unit testing in Java, provides the basic plumbing for developers to quickly generate whole test suites that validate their programs with the click of a button. With JUnit, a major excuse for eschewing unit tests has been obviated.
"Trade"-offs
However, there is a more pernicious obstacle to unit testing system parts that involve access to a database system. As an example, imagine a system that processes trade transactions in a stock market simulator. One or more external systems place trade orders into a database, which our simulator then reads and processes. Assume our goal is to implement this system as well as all the unit tests necessary to ensure its smooth run. You can easily test certain system parts with JUnit.
Now consider the object that calculates the transaction's dollar value. The test could simply create a Trade object with the desired arguments, and then assert that the getPrice() method returns the expected amount. But what about the TradeProcessor object, which reads and processes the incoming database requests? Suppose myriad combinations of incoming trade orders have different outcomes in our simulator, and we wish to test those various combinations as part of our JUnit suite. Could you unit test that part of the system? (If you're not convinced you can by the end of this article, I haven't done my job!)
We could approach unit testing this core logic in several ways. We could set up multiple test databases (one for each test case), and between each unit test, change the database the program queries. We would have to ensure that those databases are immutable, since we want subsequent runs to produce identical results. If the system's nature is such that merely running a test causes the database to produce different results (for example, by setting the status of "pending" trades to "processed"), this approach is very problematic indeed. What's more, you would then have to somehow keep all those databases, with their precise state necessary for successful unit tests, stored with that source code version. For most source code revision-control tools, this requirement would present a major problem.
Another approach might start with an empty database, and have each unit test populate it with the requisite data before executing the code to test. We would need to clean out the database between each test, so that tests could run in any order. Besides being potentially resource-intensive, this approach still suffers from the revision-control problem noted above (i.e., what if the database schema changes and becomes incompatible between releases?). Again, we are back to managing different database versions to test different software versions. Unit testing should be more seamless than this.
Fortunately, a more elegant solution exists that lets you unit test code that accesses databases, and tightly couple the code version to the database version the code expects to see, allowing both to version together in your source code repository. The solution involves, as you might expect, the subject of another mantra frequent JavaWorld readers know well: design patterns . More on those in a moment. First, we must decide on a test data form.
The X factor
Ideally, our test data should be self-contained and easily version-controlled. We would need a text format compatible with most version-control systems, and a human-readable form, which would ease test data creation and debugging. Due to relational data's hierarchical nature, a flat text file is not expressive enough without some implicit assumptions. Fortunately, our good friend XML (Extensible Markup Language) fits the bill perfectly. It is text, human-readable (when formatted properly), and easily expresses hierarchical structures. If we encode the whole test data set for a particular test as a single XML file, we can construct that file with a simple text editor, and easily version-control it right alongside the code for which it provides test data.
So, how do we create an XML document that simulates a database? The following XML "database" format was created for a real-life testing scenario, and works for most common querying scenarios. Let's suppose we want to model a database having two common queries, which we'll label "query1" and "query2" . "query1" takes one argument and returns two text columns. "query2" takes two arguments and returns one numeric column. The following XML document represents one possible database state:
value 1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10
11
When queried, this particular database returns a ResultSet with one row if "query1" executes with an argument of value 1 . A call to getString(1) on the ResultSet (i.e., get the value of the first column as text) returns value 2 . A call to getString(2) (the second column) returns value 3 . A subsequent call to resultSet.next() returns false, since only one result exists in the result set. Similarly, executing "query1" with a value 4 argument returns a ResultSet with two hits. And, executing "query2" with value 9 and value 10 arguments returns a ResultSet with one hit. A call to getInt(1) on this ResultSet returns the integer value 11 .
Although this XML database's structure is fairly simple, I've included a DataSource.dtd you can use to validate your XML data source documents for particularly large data sets.
Have I got a Bridge to sell ya
The first step toward achieving full unit-testability is to "abstract away" those system parts required to always act a certain way, but implemented differently in different circumstances. Let's assume we wish to retrofit a running application for testing. Here is TradeProcessor 's core logic, as it runs currently:
public final void processPendingTrades()
throws Exception
{
final String query =
"select id, account, transtype, symbol, quantity,
status " +
"from trades where status=
'" + Trade.STATUS_PENDING + "'";
Connection con = null;
Statement stmt = null;
ResultSet resultSet = null;
try
{
con = DriverManager.getConnection
("jdbc:db2:tradeDB");
stmt = con.createStatement();
resultSet = stmt.executeQuery(query);
while (resultSet.next())
{
final String id = resultSet.getString(1);
final String account = resultSet.getString(2);
final String transType = resultSet.getString(3);
final String symbol = resultSet.getString(4);
final int quantity = resultSet.getInt(5);
final String status = resultSet.getString(6);
final Trade trade =
new Trade(id, account,
transType, symbol, quantity, status);
process(trade);
}
}
finally
{
if (resultSet != null)
resultSet.close();
if (stmt != null)
stmt.close();
if (con != null)
{
con.rollback();
con.close();
}
}
}
This fairly standard code executes a query and steps through the result set, processing each row. When we run the application for real, the TradeProcessor must retrieve a list of currently pending trades from the database. In test mode, the TradeProcessor should retrieve that list from an XML file constructed specifically to test a particular situation.
An elegant, object-oriented approach to this problem inserts an abstraction layer between the processing logic and the implementation. In other words, the processing logic continues to act on an object that behaves like a ResultSet , but which may or may not actually talk to a real Java Database Connectivity (JDBC) database. The object represents abstractly a " ResultSet -like" object. The point is that the processing logic only cares that the object it talks to responds to commands such as next() and getString() . This approach of creating an interface for which the implementation may vary is so common in object-oriented programming that it has earned the distinction of being identified as the Bridge design pattern.
The solution then creates a new set of abstract types that capture the abstract nature of querying a data source and retrieving results. In addition to the ResultSet type, we must also create a DataSource type (which represents either the database or the XML file), and a Query type (which, when passed to the DataSource , allows the DataSource to create a ResultSet ).
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Pattern your way
to automated regression testing
View Tutorial: Pattern your way
to automated regression testing
Related
Tutorials:
|
Displaying 1 - 50 of about 2348 Related Tutorials.
|
GJTester - Java Unit Testing Tool
tool, accomplishes the
unit, regression and contract testing of your Java... modules without
implementing test clients
Regression testing
In case...
GJTester - Java Unit Testing Tool
GJTester - Java |
Continuous Testing
, download v 1.2.1,
2) Continuous Testing 2.0 for Eclipse 3.2 is on the way
3) Join...
Continuous Testing
Continuous Testing...;
Continuous testing uses excess cycles on a developer's
workstation |
Eclipse Plunging/Testing
for the automated testing of
Graphical User Interfaces (GUI's), with a focus on programs...++ Unit Testing Easier
Automated unit testing supports high quality of program... is a platform for automated testing of distributed software systems.
These include |
Open Source Testing
functional testing tool. It includes an HTTP proxy that records your test script...;
Automated Open Source Testing and Certification
SpikeSource, a starry Redwood City...
Open Source Testing
Open Source Testing
Open Source |
Pattern resetting using regular expression
Pattern resetting using regular expression
Pattern resetting using regular expression
 ... describes the way to retrieve the String using regular expression. For
this we |
AppPerfect Unit Tester
testing of
each smallest logical unit of your software. This unit may be a module... of your testing infrastructure. As you
develop new "units" of your... for their
applications and can use these test cases for regression testing |
Design Pattern
Design Pattern
Design Pattern
 ...;
?Pattern?
word suggests a series of events occurring in a definite order. Many a times,
you get an easy way to tackle a recurring problem (which has been faced |
The Cheapest Way To Speed Up Your PC
The Cheapest Way To Speed Up Your PC
The Cheapest Way To Speed Up Your PC
 ...;
Matt Feichtenbiner
Is your computer |
Matching Pattern using Regularexpression
Matching Pattern using Regularexpression
Matching Pattern using Regularexpression
 ...;
This Example describe
the way |
Cute C++ Unit Testing Easier
;
Automated unit testing supports high quality...
Cute C++ Unit Testing Easier
Cute C++ Unit Testing...
testing because of JUnit and its tight integration into IDEs like Eclipse. C |
What is Solex ?
;
Solex is a free open source Web application testing tool built... in order to ensure non regression of
the application's behaviour (with stress testing capabilities being added at a
later stage).
By recording, we mean |
JUnit Training
. It's a regression-testing framework that developers can use to write unit tests... time when you make any changes in your code during the development. It
ensures that modifications in the code will not break your system without your
knowledge |
Testing Struts Application
files as needed, restart your container, and you are on
your way! (You can find...
Testing Struts Application
Testing... the
corresponding display as follows:
Welcome!
To get started
on your own |
How To Manage Your Username And Password The Easy And Secure Way
How To Manage Your Username And Password The Easy And Secure Way
How To Manage Your Username And Password The Easy And Secure Way
  |
Cantata++ - for testing C and C++ software
and Integration Testing
Automated Test
Script Generation by parsing source...
Cantata++ - for testing C and C++ software
Cantata++ - for testing C and C++ software
  |
Open Source Automated Test Tools written in Java
|
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
 ... learn the way of
detecting all special characters present in the given string |
Open Source Automated Test Tools written in Java
|
GUIdancer
;
GUIdancer is a powerful
Eclipse-based tool for the automated testing of Graphical User....
No programming at any stage
of the testing process
Maintainable... capacity
Multi-lingual testing
Platform-independent |
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
 ... learn the way of
detecting all special characters present in the given string |
Writing and testing method of addition of two numbers
Writing and testing method of addition of two numbers
Writing and testing method of addition of two numbers
 ... involved in testing with JUnit. In this section, we will be creating a
java file |
Compiling and testing the application
Compiling and testing the application
Compiling and testing the application
 ... and to compile the project go to
the project\WEB-INF\src of your poject and then use |
Compiling and testing the application
Compiling and testing the application
Compiling and testing the application
 ... and to compile the project go to
the project\WEB-INF\src of your poject and then use |
How to Backup Your Computer Files
How to Backup Your Computer Files
How to Backup Your Computer Files
 ... we need most. Consider this: When was the last time you backed up your computer |
Testing EntityReferences in Xml
Testing EntityReferences in Xml,XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials
Testing EntityReferences in Xml...;
This Example gives you the way to test EntityReferences in an XML file. JAXP (Java |
VoIP Keep Your Number
VoIP Keep Your Number
VoIP Keep Your Number...;
VoIP Keep Your Existing Phone Number
Changing your... your existing phone number. To do this, simply sign up and select the option |
Get Noticed with Your Resume
Get Noticed with Your Resume
Get Noticed with Your... the importance of your resume- they tell you that your resume can make or break your chances to get to the interview. No matter how often repeated, this point |
Your Computer Sick
Your Computer Sick
Your Computer...
Viruses and spyware usually show up on your computer one of two ways.
1-Either they invade your system with a frontal assault like the Huns attacking |
Why SCADA?
. SCADA is a control system with applications in managing large-scale, automated..., you can eliminate the need for site visits by your personnel for inspection... the life-period of your equipment and save on the need for costly repairs |
Your competitor presses you to reveal some confidential information about your current or previous employer.
in their den.
Another reason could be that the company is testing your integrity...
Situation: Your competitor presses you to reveal some confidential information about your current or previous employer.
Situation |
Building and Testing Struts Hibernate Plugin Application
Building and Testing Struts Hibernate Plugin Application
Building and Testing Struts Hibernate Plugin Application....
Deploying and testing application
Copy strutshibernate.war  |
Running and Testing Struts 2 Login application
and Testing Struts 2 Login application
 ... on startup.bat. The startup.bat will start the tomcat.
Testing application
To test the application type http://localhost:8080/struts2tutorial/.
Your browser should |
Listing Directory using Regular expression
is for
testing if a specified file should be included in a file list.
pattern... the way
how to list the directory by using Regularexpression.The steps involved... this example
create your own directory and give the path of the directory.String |
Get Your Game on with SuperGamer-1
Get Your Game on with SuperGamer-1
Get Your Game on with
SuperGamer-1
Gaming in Linux is much easier than
it once... for hardware compatibility before
committing the distribution to your hard drive. You |
What would you rate as your greatest weaknesses?
What would you rate as your greatest weaknesses?
What would you rate as your greatest weaknesses?
 ... weakness, you will be respected for your honesty, but your resume will end up |
Improve Your Assertiveness at Work
.
Mind the way you speak with others. When you express your ideas and opinions...
Improve Your Assertiveness at Work
Improve Your... as anyone else. Affirm these thoughts in your mind.
Do you have a tendency |
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
 ... how to compile a pattern
with multiple flags like multiline, case insensitivity |
Rid Your Computer of ITD - Internet Transmitted Diseases
Rid Your Computer of ITD - Internet Transmitted Diseases
Rid Your Computer of ITD - Internet Transmitted... but there are some things you can do to limit your infection by it.
Check to see |
Rid Your Computer of ITD - Internet Transmitted Diseases
Rid Your Computer of ITD - Internet Transmitted Diseases
Rid Your Computer of ITD - Internet Transmitted... but there are some things you can do to limit your infection by it.
Check to see |
Controlling your program
Controlling your program
Controlling your program... in Java is the best way to test a single expression against a series
of possible... = " + i);
}
There is a simpler way to declare and initialize the variable |
Watch Out For Spyware Programs That Slows Down Your Computer System
and save anything on your computer.
The best way to combat spyware...
Watch Out For Spyware Programs That Slows Down Your Computer System... Your Computer System
  |
This series of progressive examples shows a typical pattern for building simple applications with a window.
NotesAbout Examples
This series of progressive examples shows a typical pattern... beginning of the pattern that will
be used in many examples in these notes.
Example - ToUppercase is an application that
extends the above pattern |
Iterative/Incremental Development
design.
Testing - This is the process of trying to detect errors in the program.
For large programs this is typically divided into two parts: unit testing
tests individual modules and integration testing sees if the total program |
Pattern and Matcher
Java: Pattern and Matcher
Java: Pattern and Matcher
In addition to the regular expression methods... pattern can be reused by many Matcher
objects.
Pattern pat |
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
 ... how to compile a pattern
with multiple flags like multiline, case insensitivity |
Factory Pattern
Factory Pattern
Factory Pattern
 .... Factory Pattern:
One of the goals of object-oriented design..., not what kind of subclass
to create.
Creational design pattern , more |
I Terribly Wrong In Your Computer
terrorist half way across the world. Protect your PC and your identity. You...
I Terribly Wrong In Your Computer
I Terribly Wrong In Your Computer
  |
Watch Out For Spyware Programs That Slows Down Your Computer System
and save anything on your computer.
The best way to combat spyware...
Watch Out For Spyware Programs That Slows Down Your Computer System... Your Computer System
  |
Alvicom LoadManager
;
Our LoadManager testing tool focuses on Load, Stress.... The outcome is a reliable test tool which offers
the most efficient testing process...:
1) LoadManager is sold as
a customizable tool. We discuss your needs |
Design patterns interview questions
patterns interview questions1
A pattern is a proven (and recurring)
solution to a problem in a context. Each pattern describes a problem...
solution to this problem in such a way that we can use this solution |
|
|
|