I am looking for ways / best practices on testing methods defined in an abstract base class. One thing I can think of directly is performing the test on all concrete subclasses of the base class, but that seems excessive at some times.
Consider this example:
import abc class Abstract(object): __metaclass__ = abc.ABCMeta @abc.abstractproperty def id(self): return @abc.abstractmethod def foo(self): print "foo" def bar(self): print "bar"
Is it possible to test bar
without doing any subclassing?
The answer is: always test only concrete classes; don't test abstract classes directly . The reason is that abstract classes are implementation details. From the client perspective, it doesn't matter how Student or Professor implement their GetSignature() methods.
A class is called an Abstract class if it contains one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.
In Python, abstract base classes provide a blueprint for concrete classes. They don't contain implementation. Instead, they provide an interface and make sure that derived concrete classes are properly implemented. Abstract base classes cannot be instantiated.
Introduction to Python Abstract Classes In object-oriented programming, an abstract class is a class that cannot be instantiated. However, you can create classes that inherit from an abstract class.
In newer versions of Python you can use unittest.mock.patch()
class MyAbcClassTest(unittest.TestCase): @patch.multiple(MyAbcClass, __abstractmethods__=set()) def test(self): self.instance = MyAbcClass() # Ha!
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