Search code examples
ooptddtell-dont-ask

How to test an object when I can't access state?


I have a factory class that creates an object based on a parameter it receives. The parameter is an identifier that tells it which object it should create. Its first step is to use the data access layer to pull information for the object. Its next step is to do some cleansing / transformations on the data. Finally it creates the required object and returns it.

I want to ensure that the cleansing / transformation step went OK but the object that it returns does not expose any state so I'm not sure how to test it easily.

The data access layer and the database structure can't change because they have to work with legacy code.

I could test it further on in the system after the object gets used but that would lead to big tests that are hard to maintain.

I've also thought of exposing the state of the object, or putting the responsibility in another class and testing that, but both those options seem like I'm changing the system for testing.

Any thoughts on other ways to test something like this?


Solution

  • It sounds to me like you are trying to test too much within a unit test.

    This is a symptom of your Unit trying to do too much.

    You are trying to do three things here.

    1. Get data from the data access layer.
    2. Clean the data.
    3. Build the object

    To fix I would move each of these responsibility into their own units ( classes / methods ) as you have suggested. Then you can test each unit on its own.

    You are hesitant to do this as you don't want to change the system for testing. However, the advantage of unit testing is that it highlights flaws in the design. Not only are you changing the system for testing, you are improving it and making it more granular and thus more maintainable and reusable.