I’m looking for some design advice for a new module of the application I am working on, particularly with regards to how to make the design testable.
The problem is very common – load some data from a database, run some operations against the data, and save the result to the database. Most other modules in the application have the following pattern:
private repo; //Set in constructor
public void Run()
{
Stuff stuff = repo.LoadStuff()
Result result = RunOperationsInPrivateMethod(stuff); //private method
repo.SaveResult(result);
}
So to test this, I see that I have a couple of choices:
- Inject a mock repo that I can use to return a Stuff and verify a Result.
- Refactor RunOperationsInPrivateMethod to protected access, and test
the operations directly.
Am I missing any other options? What are peoples preferences?
In general, don’t test private methods, instead, think whether your private method really should be a public method of another class. ie, decompose your object into smaller objects with focused functionality.
eg, perhaps Run should be
then Run would be a public method of an operations class
Then also, you wouldn’t have to load a Stuff from a database to test, just create a stuff in a fixture focused on testing SecretOperation. Now your unit tests can be more focused.