Should classes, that modify the state of the parent class, but not itself, be unit tested separately? And by separately, I mean putting the test in the corresponding unit test class, that tests that specific class.
I’m developing a library based on chained methods, that return a new instance of a new type in most cases, where a chained method is called. The returned instances only modify the root parent state, but not itself.
Overly simplified example, to get the point across:
public class BoxedRabbits
{
private readonly Box _box;
public BoxedRabbits(Box box)
{
_box = box;
}
public void SetCount(int count)
{
_box.Items += count;
}
}
public class Box
{
public int Items { get; set; }
public BoxedRabbits AddRabbits()
{
return new BoxedRabbits(this);
}
}
var box = new Box();
box.AddRabbits().SetCount(14);
Say, if I write a unit test under the Box
class unit tests:
box.AddRabbits().SetCount(14)
I could effectively say, that I’ve already tested the BoxedRabbits
class as well. Is this the wrong way of approaching this, even though it’s far simpler to first write a test for the above call, then to first write a unit test for the BoxedRabbits
separately?
3
If the class really is as trivial as that and the rest of your test suite is sufficiently complete, then there’s a fairly high degree of certainty that the test coverage of the trivial class is pretty high and any change to that class’s API or functionality will inevitably affect several unit tests. If that’s the case, I’d do without the additional unit test.
If, however, the class went beyond non-trivial and involved any kind of language syntax that can be changed from anywhere else in the source (a header that defined configuration variables/typedefs), or data structures that are implementation-dependent, then I would certainly create a unit test.
My rule of thumb is if it has flow control then it has a unit test. That may not always be true but simple code usually has simple unit tests. Therefore testing simple code usually isn’t that big a burden. So why not make sure you didn’t accidentally think less than and type greater than?