October 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Using Randomization in Java Unit Testing

  • January 13, 2010
  • By Bob Reselman
  • Send Email »
  • More Articles »

Working with the QaRandomizer

Table 1 below describes the methods that make up the QaRandomizer. Again, notice that there are methods that generate random first name, last name, full name, address structure, and email addresses. There are methods that provide lists of the internal data against which randomization is performed. Lastly, the QaRandomizer provides a method that allows you to retrieve a random item from a typed list.

Table 1. The Methods That Make Up the QaRandomizer API
QaRandomizer Class Method Class Function
RandomAddress getAddress() Gets an instance of the RandomAddress object
protected RandomAddress getAddressFromZipCode(java.lang.String zipcode)  
protected java.util.Set<java.lang.String> getAddressTwoTypeList() Gets the list of strings that are used to construct AddressTwo, such as "suite", "room", "mailstop", etc.
protected java.util.Random getClassRandom() The accessor that retrieves the class instance of the Random object
java.lang.String getComplexString(int maxLength) Gets a random complex string (A complex string includes all alphanumeric characters, plus extended characters such as @%^$*, etc.—Example: wDr56$*c0Q)
java.lang.String getEmailAddress() Gets a random email address
java.lang.String getExtendedString(int maxLength) Gets the random Extended string, which can include all alphabetic characters, upper and lower case plus extended characters such as @%^$*, etc.—Example: qwGfdiuR$#
java.lang.String getFirstName() Gets a random first name
protected java.util.Set<java.lang.String> getFirstNamesList() Gets the internal list of first names from which a random first name is extracted
java.lang.StringgetFullName() Gets a random full name for a person
protected com.edmunds.training.utilities.qarandomizer.QaRandomizerHelper getHelper() Gets the QaRandomizerHelper class that provides access to the internal XML files that contain address by zip code information, first name, and last name data
static QaRandomizer getInstance() Gets the singleton instance of QaRandomizer
java.lang.String getLastName() Gets a random last name
protected java.util.Set<java.lang.String> getLastNamesList() Gets the internal list of last names from which a random last name is extracted
<T> getRandomItem(java.util.Set<T> set) This method allows you to get a random item from a Set of type T
java.lang.String getSimpleString(int maxLength) Gets the random Simple string, which can include all alphabetic characters, upper and lower case
java.lang.String getSSN() Provides a random social security number in the format ddd-dd-dddd
protected java.util.Set<java.lang.String> getStreetNameList() Gets the street name list, based on a set of internally defined values
protected java.util.Set<java.lang.String> getStreetTypes() Gets a Set that contains street address types, such as St., Ave, Blvd, etc.
java.lang.String getZipCode() Gets a random zip code
protected java.util.Set<java.lang.String> getZipCodesList() Gets the internal list of zip codes from which a random zip code is extracted

The sections that follow describe the features of the QaRandomizer in detail.

Getting a Random Name Value

The QaRandomizer provides three methods that you can use to work with names on a random basis:

  • getFirstName()
  • getLastName()
  • getFullName()

Listing 2 above uses these methods. They return a random first name, last name, or full name from a list of first and last names described in XML files that are embedded as resource files in the QaRandomizer project.

Figure 2 below illustrates the way that first name, last name, and zip code XML files are processed by the QaRandomizer code.


Figure 2. QaRandomizer XML-to-Java Conversion:
The QaRandomizer uses dom4j to convert XML files into a DOM Java objects.

You can use the methods getFirstNamesList() and getLastNamesList() to retrieve the first and last names in force.

Working the Random Address Object

As mentioned previously, the QaRandomizer provides the ability to generate random address data within a RandomAddress object. Address data is constructed by randomly selecting a US zip code, with its related city and state, from an XML file embedded as a Java resource in the QaRandomizer binary. After the city, state, and zip are extracted from the XML file, a fictitious street address and a secondary address are constructed randomly.

Listing 4 shows you how to use the QaRandomizer.getInstance().getAddress() method to get a random address.

Notice that the QaRandomizer is a Singleton. Using the Singleton pattern allows all the XML data in the embedded resource files to load into the QaRandomizer internals once, upon module initialization.

Using Randomization with Mock Objects

The trick with unit testing is to test one unit of functionality. Usually that unit is a method. Testing the integrity of an entire class is typically relegated to integration testing. Many times when you are testing a method, you need to work with code that has yet to be written. In cases such as this, you use mock objects. (You can learn more about using mock object here.)

Testing the send() method of the PostServiceImpl object requires that you use a mock object. (PostOfficeImpl is an implementation of the PostOffice interface.) The send() method delegates dispatching letters and emails to an internal object that implements the PostalDispatch interface. However, the dispatch object that will implement PostalDispatch has yet to be written. Thus, you implement the PostDispatch interface into a mock object.

Listing 5 below demonstrates the use of a mock object to emulate unimplemented behavior in a testing scenario associated with the PostOfficeImpl object.

Listing 5: A Test That Uses a Mock Object to Verify Use of an Unimplemented Interface, PostalDispatcher
@Test public void sendEmailViaPostOfficeTest() throws QaRandomizerException { // Set up the mock for the PostalDispatcher interface PostalDispatcher mockDispatcher = createMock(PostalDispatcher.class); // Set the mock Dispatcher to the Post Office object PostOfficeImpl.getInstance().setDispatcher(mockDispatcher); // Get an Email with data from the QaRandomizer Email email = getRandomEmailWithBody(); // Tell the mock framework to expect a call to the // dispatch() method mockDispatcher.dispatch(email); // Register the mock scenario replay(mockDispatcher); // Call the behavior that we're testing for PostOfficeImpl.getInstance().send(email); // Verify that the test passed verify(mockDispatcher); }


The mock scenario in Listing 5 is looking for a call to the mockDispatcher.send() method, requires that an email address be provided. Now, you could have unwittingly used a hard-coded email address to satisfy that requirement. But you've thought ahead and brought the habit of using randomization to your unit test. Thus, using the code shown in Listing 6 below in conjunction with the code in Listing 5, you can leverage the QaRandomizer.getEmailAddress() method to easily create to a unit test the meets testing requirements under a very broad condition.

Listing 6: A Private Method That Uses a Random Email Addresses
private Email getRandomEmailWithBody() throws QaRandomizerException { // Make the random data string data String body = QaRandomizer.getInstance().getComplexString(400); //Create a random to email address String toEmail = QaRandomizer.getInstance().getEmailAddress(); //Create a random from email address String fromEmail = QaRandomizer.getInstance().getEmailAddress(); // Create the Email object Email email = new Email(toEmail, fromEmail, body); // return it return email; }


Get a Random Item from a Typed List

The QaRandomizer is designed to provide basic randomization services that you can use in many situations. However, at some point you most likely will want to use randomization from a list of data that you designed. In such cases, you use the QaRandomizer.getRandomItem(Set<T>) method, which takes as a parameter a list of objects of the same type. Thus, you provide to the method a list of data-filled objects (Beans, for example). The QaRandomizer.getRandomItem(Set<T>) method will randomly choose an object to return from the list passed in as a parameter.

Listing 7, in conjunction with Listing 6 and Listing 8, shows you how to use getRandomItem(). The scenario that these code listings illustrate is creating a finite list of email addresses and then running a test that selects a random item from that finite list.

Listing 7: Getting a Random Object From a Strong Typed List in Conjunction With a Mock Object
public void sendEmailFromFiniteListTest() throws QaRandomizerException { // Get a list of 6 email addresses Set< Email>emails = getListOfEmails(6); //Set up the mock for the PostalDispatcher interface PostalDispatcher mockDispatcher = createMock(PostalDispatcher.class); // Set the mock Dispatcher to the Post Office object PostOfficeImpl.getInstance().setDispatcher(mockDispatcher); // Get an Email with data from the finite list of email addresses Email email = QaRandomizer.getInstance().getRandomItem(emails); // Tell the mock framework to expect a call to the // dispatch() method mockDispatcher.dispatch(email); // Register the mock scenario replay(mockDispatcher); // Call the behavior that we're testing against PostOfficeImpl.getInstance().send(email); // Verify that the test passed verify(mockDispatcher); }

Listing 8: Creating a HashSet<Email> List
private Set< Email> getListOfEmails(int listCount) throws QaRandomizerException { //Create the strong typed list Set<Email> emails = new HashSet<Email>(); //Iterate through and add an email with body to the list for (int i = 0; i < listCount; i++) { Email email = getRandomEmailWithBody(); emails.add(email); } return emails; }


Granted, creating a list with a predefined number of email addresses is a bit trivial. However, you can easily expand the concept illustrated in Listings 6-8. Suppose that you had to write a test that required automobile data. You can create an object that describes an automobile and then populates a HashSet of such Automobile objects with data as you add each Automobile to the list (see Listing 9).

Then you can use getRandomItem() to return a random Automobile from that strong typed list as shown below in Listing 10.


Tags: Java, XML, TDD, Unit Testing, Mock Objects



Page 2 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel