Say we have this hyper simple class hierchy:
public class SomeMath
{
public int Add(int x, int y)
{
return x + y;
}
}
public class MoreMath : SomeMath
{
public int Subtract(int x, int y)
{
return x - y;
}
}
Should I write tests for the Add
method when I write tests for the MoreMath
class? Or should I only care about that method when I am testing the SomeMath
class? More generally: Should I test all methods of a class, or should I only test "new" methods?
I can kind of come up with some reasons for both sides. For example, when testing all methods you will end up testing the same thing more than once, which is not so good and can become tedious. But if you don't test all methods, a change in SomeMath
might break usages of MoreMath
? Which would kind of be a bad thing too. I suppose it probably depends a bit on the case too. Like if it extends a class I have control over or not. But anyways, I'm a total test newbie, so I am curious to know what people smarter than I think about this :-)
Normally I wouldn't test behavior in the child class unless the child class changes the behavior from that expected in the parent class. If it is using the same behavior, there is no need to test it. If you are planning to make breaking changes to the parent class but the child class still needs the old behavior, then I would first create tests in the child class to define its required behavior, then I would make the changes in the parent tests and subsequent code changes. This follows the YAGNI principle -- you aren't going to need it -- and delays the implementation of the child tests until they actually have a purpose.
I'd only test the Add
method of the SomeMath class. If MoreMath
only inherits it and does absolutely nothing new, then writing tests for both would be pure duplicate code, nothing more. It's always good to be a little pragmatic with these things imho.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With