Helgevold Consulting, LLC

How To Remove Data Dependencies In Unit Tests

A common problem when writing unit tests is data dependency. Typically when you are writing tests for a method, the same method is making a call to another method which makes a call to some external data source. Code listing 1 illustrates this: The SellStock method depends on the value returned from StockService.


Code Listing 1

I feel this dependency is undesirable in the context of a unit test, and the following is a technique I commonly use to remove this dependency:

Instead of calling StockService.GetStockValue directly, I move the call into a protected virtual method as illustrated in code listing 2:


Code Listing 2

The idea is that the test class can inherit the Trader class and override GetStockVaule to return a predefined value.

Code listing3 illustrates this:


Code Listing 3

The result is that we can test the SellStock method without having to call the StockService. I personally use this technique extensively when writing unit tests and feel it’s a really good way to abstract data dependencies.


Vote this article up or down (0)
You comment has been saved. It will appear as soon as we have approved it
Please fill out all fields

Feel free to comment on this article!

Your name


Title


Your comment




Written by
Torgeir Helgevold

Date
9/6/2010 11:02:04 PM

Title
Stub class

As an alternative you can create a stub class and have the stub class, instead of the test class, inherit from the Trader class.