01.02.2013 Views

Software Development Cross Solution - Index of - Free

Software Development Cross Solution - Index of - Free

Software Development Cross Solution - Index of - Free

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

using a mock object framework<br />

Mock objects are working object stand-ins<br />

Let’s look at a mock object framework in action. Below is a test that uses the EasyMock<br />

framework, a mock object framework for Java. A good mock object framework allows you to<br />

simulate an object’s behavior, without writing code for that object.<br />

This is<br />

all “normal”<br />

test code...<br />

no mock<br />

objects<br />

involved yet.<br />

import org.easymock.*;<br />

// This test will test placing an order with a valid gift card<br />

// with exactly the right amount <strong>of</strong> money on it.<br />

@Test<br />

public void testSimpleOrder() {<br />

// Set everything up and get ready<br />

OrderInformation orderInfo = new OrderInformation();<br />

orderInfo.setCustomerName(“Dan”);<br />

orderInfo.setDrinkDescription(“Bold with room”);<br />

orderInfo.setGiftCardNumber(12345);<br />

orderInfo.setPreferredStoreNumber(123);<br />

Date activationDate = new Date(); // Valid starting today<br />

Date exiprationDate = new Date(activationDate.getTime() + 3600);<br />

BigDecimal gcValue = new BigDecimal(“2.75”); // Exactly enough<br />

GiftCard startGC =<br />

new GiftCard(activationDate, expirationDate, gcValue);<br />

BigDecimal gcEndValue = new BigDecimal(“0”); // Nothing left<br />

GiftCard endGC =<br />

new GiftCard(activationDate, expirationDate, gcEndValue);<br />

// Here’s where the mock object creation happens<br />

DBAccessor mockAccessor = EasyMock.createMock(DBAccessor.class);<br />

306 Chapter 8<br />

Whatever framework<br />

you use, you’ll need to<br />

import the right classes.<br />

We want an object that<br />

implements this interface......so we tell our framework to create a mock<br />

object that implements the right interface.<br />

At this point, the mock object framework doesn’t know much—just that<br />

it has to create a stand-in for the DBAccessor class. So it knows the<br />

methods it “mocks”, but nothing more than that—no behavior yet at all.<br />

Download at WoweBook.Com<br />

This is all part <strong>of</strong> the<br />

test orderInfo object<br />

we want to use.<br />

This sets up test values<br />

that we’ll use in the<br />

GiftCard we’re testing.<br />

We need a gift card representing the<br />

starting values we’re testing...<br />

...and then an<br />

“ending” gift<br />

card. This has<br />

what should be<br />

returned from<br />

testing order<br />

processing.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!