Confused about why it's useful to unit test dummy objects

Viewed 613

I'm reading Clean Code: A Handbook of Agile Software Craftsmanship and one of the examples involves a Portfolio class and a TokyoStockExchange class. However, Portfolio is not very testable because it depends on TokyoStockExchange as an external API to determine the value of the portfolio and such is quite a volatile lookup and not conducive to testing.

So, they solve this by creating a common StockExchange interface and have TokyoStockExchange and DummyStockExchange both implement the base class. Thus, dependency inversion principle is attained and in the PortfolioTest class one can instantiate a DummyStockExchange, fix a stock price to a corporation, assign the DummyStockExchange instance to the portfolio, and add some stocks from that company to the portfolio, and then assert if the expected value is indeed the proper value. Here's the code:

public class PortfolioTest
{
    private DummyStockExchange exchange;
    private Portfolio portfolio;

    protected void setUp()
    {
        exchange = new DummyStockExchange();
        exchange.fix("MSFT", 100);
        portfolio = new Portfolio(exchange);
    }

    public void GivenFiveMSFTTotalShouldBe500()
    {
        portfolio.add(5, "MSFT");
        Assert.assertEquals(500, portfolio.value());
    }
}

My question, simply, is why?

We were trying test if the TokyoStockExchange class worked in tandem with the Portfolio class. Obviously if we create another class with a new method that sets a stock price and then give the portfolio five of those stocks then everything will work. It just seems.. useless to test. I understand that TokyoStockExchange is basically impossible to test with Portfolio because of the changing stock prices but I don't understand how subbing in a rather useless test helps the situation.

It all just seems akin to not knowing if our adder programs works but the only numbers available are randomly generated so we create a dummy class that gives us a 2 and test if 2 + 2 = 4. Well yeah, obviously that is true. We can still break TokyoStockExchange and the test will still succeed because it's testing another class. If anything this all seems deceptive and it also results in having to write additional code just to test something we know is going to work.

I think this is the biggest problem I have with understanding Unit Testing at this point. I know that I'm wrong I just have failed to see the light I guess. Hopefully someone can help me out.

2 Answers
Related