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.