Tommy writes in on my book forum:
This is an real world example method where I'm confused how to unit test.
public List<RuleDescription> PrepareCandidates(RuleDescription ruleDescription, RuleType ruleType)
List<RuleDescriptionType> ruleDescTypeList = _dataAccessor.GetRuleDescriptionTypeList(ruleType);
List<RuleDescription> ruleDescriptionList = new List<RuleDescription>();
foreach (RuleDescriptionType type in ruleDescTypeList)
The classes RuleType, RuleDesctiptionType and RuleDescription contains many attributes which some are other complex objects.
The method does not contain any real logic, just adding data to lists from a database (through the _dataAccessor-object).
Does that mean that I should not unit test this method? Or does it mean that the method is poorly designed? Can or should I mock the _dataAccessor-object?
Lets say that the method returns 5 elements in the list for given parameters (with say 6 importants attributes in each). That's a lot of data to prepare for a test if I want to write expectations for the return value of the method.
I often stumble in to these situations when I'm unit testing where I become overwhelmed by the amount of data I have to insert. I guess I have the wrong approach, but where do I think wrong?
Heres my answer:
I would test this method as it does contain some form of logic (a loop).
There are two ways to test it:
- Integration test: Use the real database (data accessor) which forces you to have this data available somewhere and have everything running.
- unit test: That is what I'd go for here I think.
here is how you could unit test this:
- Stub out the data accessor to return only 1-3 values (remember to write the test a simply as possible to prove your point), and only send in 1-3 values to the method, and assert that you get back an expected collection.
- What you are testing is: that it loops on all of them, and that is asks for data from the accessor
, so your tests need to vary on the nuber of objects being passed in, and the data returned from the stub accessor (at least two or three tests I would think).
- when these three pass, you can be certain to a degree that the method does what its supposed to do.