I’ve got a set of actions which share some base checks. My code looks like this:
def is_valid(param): …some pretty complex things unit-tested on their own…
class BaseAction(object):
def run(self, param):
if not is_valid(param):
raise ValueError(…)
return self.do_run(param)
class Jump(BaseAction):
def do_run(self, param): …
class Sing(BaseAction):
def do_run(self, param): …
How should I unit-test the fact that BaseAction.run performs validation?
I think I could unit-test Jump.run and Sing.run, but then to do it properly I’d need to write tests for each subclass of BaseAction, potentially quite a lot of cases. Also this means coupling test for subclasses with a test for base class’ method.
You would unit-test the
is_valid()function itself. You then only have to test for the fact that.run()raises aValueErrorexception when passed invalid input:Since you already have a unittest for
is_valid()itself, your unittests for.run()do not need to focus on it’s functionality. You can focus on the functionality unique to.run().In your case
BaseActionis a unit providing a service to subclasses; I’d test this as a mock subclass:so you can check if
runindeed calleddo_runwith the expectedparamvalue.