developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
KVM Switch over IP
Computer Deals
Laptop Batteries
Laptops
PDA Phones & Cases
Televisions
Imprinted Gifts
Shop
Memory
Home Improvement
Promotional Gifts
Promos and Premiums
Promotional Products
Holiday Gift Ideas

 


Web Devs:
Moonlight as a Game Developer and Win Cool Prizes by Accepting the RIA Run Challenge

Now, your mission--should you choose to accept: Take your shot at gaming stardom if you think you might have what it takes to build a cool RIA game and you could win an Xbox 360 or other fabulous prizes. Hurry! You only have until May 15, 2008 to enter. »

 
Article:
Leveraging Your Flash Development with Silverlight

You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. Learn more here. »

 
Article:
What Does it Take to Build the Best RIA?

With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »

 
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Getting Test Doubles in Place
By Jeff Langr

Go to page: 1  2  3  Next  

I'm building a portfolio manager, something that will track my stock purchases. My current need is that it calculate the total value of its contained holdings. A holding is a stock symbol and the number of associated shares. The portfolio value is the sum of the current price of each symbol times the corresponding number of shares. An external service, perhaps supplied by NASDAQ, provides the ability to look up a stock's value.

Were I to build Portfolio without considering the need to unit test it, the implementation might look like Listing 1.

Listing 1: Portfolio.

import java.util.*;

public class Portfolio {
   private Map<String,Integer> holdings =
      new HashMap<String,Integer>();

   public int value() {
      int total = 0;
      for (Map.Entry<String,Integer>
          entry: holdings.entrySet()) {
         String symbol = entry.getKey();
         int shares = entry.getValue();
         total += new NASDAQLookupService().currentValue(symbol)
               * shares;
      }
      return total;
   }

   public void purchase(String symbol, int shares) {
      holdings.put(symbol, shares);
   }
}

I code using test-driven development, so my primary interest is in ensuring that there's an easy way to drive and verify each line of code in the value method. The problem is that NASDAQ keeps returning a different value each time I send it a request for a symbol's price. The solution is to provide what's known as a "test double" for the NASDAQLookupService object. This test double will emulate the NASDAQLookupService behavior, but fix it for purposes of testing. (Other similar terms for test doubles are fakes, stubs, and mocks.)

When using test doubles, I have two primary concerns: first, what does the test double look like, and second, how do I incorporate it into the production code? With regard to the first concern, the test double is a simple implementation of the same interface used by the real object. For my Portfolio class, I create a fake StockLookupService that implements an interface named StockLookupService. NASDAQLookupService, too, implements this interface.

Now that I have a fake lookup service, how do I get it into the the class that I'm testing (the target class)? The usual solution is to pass the fake into the target via a constructor or setter. This technique is most common, and demonstrated by most introductory articles on mocking. I'll present this rudimentary injection technique, and then focus on a couple additional ways to inject the test double.

Constructor/Setter Injection

In Listing 2, I present an altered Portfolio class. The constructor provides the ability for a client to pass in a reference to a StockLookupService. This reference can of course point to either a NASDAQLookupService or to a fake lookup service.

Listing 2: An injectable Portfolio.

import java.util.*;

public class Portfolio {
   private StockLookupService service;
   private Map<String,Integer> holdings =
      new HashMap<String,Integer>();

   public Portfolio(StockLookupService service) {
      this.service = service;
   }

   public int value() {
      int total = 0;
      for (Map.Entry<String,Integer>
         entry: holdings.entrySet()) {
         String symbol = entry.getKey();
         int shares = entry.getValue();
         total += service.currentValue(symbol) * shares;
      }
      return total;
   }

   public void purchase(String symbol, int shares) {
      holdings.put(symbol, shares);
   }
}

A bit of relevant test code for Portfolio appears in Listing 3. The @Before initialize method instantiates an anonymous fake impementation of the StockLookupService. It then uses this to instantiate an instance of the target class Portfolio.

Listing 3: PortfolioTest.

import static org.junit.Assert.*;
import org.junit.*;

public class PortfolioTest {
   private static final int CURRENT_MSFT_VALUE = 100;
   private static final String MSFT = "MSFT";
   private Portfolio portfolio;

   @Before
   public void initialize() {
      StockLookupService service = new StockLookupService() {
         public int currentValue(String symbol) {
            if (MSFT.equals(symbol))
               return CURRENT_MSFT_VALUE;
            return 0;
         }
      };

      portfolio = new Portfolio(service);
   }

   @Test
   public void multiplesValueByShares() {
      portfolio.purchase(MSFT, 10);
      assertEquals(CURRENT_MSFT_VALUE * 10, portfolio.value());
   }
}

Go to page: 1  2  3  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Architecture & Design Archives

Generate Complete .NET Web Apps in Minutes . Download Iron Speed Designer today.
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.
Is it time to make your move to the multi-threaded and parallel processing world? Find out!
Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation

Oracle Information-Driven Business Center:
DVD OFFER:
Get Started with Oracle on Windows DVD
WHITEPAPER:
Will Your Database Measure Up? Oracle Database 11g vs. Microsoft SQL Server 2005
WHITEPAPER:
Innovate Faster with Oracle Database 11g
WHITEPAPER:
Oracle Application Express Overview 3.0


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES