Last Updated: February 24, 2016
·
2.209K
· kisielk

Add test cases to test classes via mixins

If you have a bunch of common tests that apply to many test classes you can add them via mixins. For example:

class MixinTests(object):
    def test_something(self):
        self.assertTrue(self.obj.something)


class FooTester(unittest.TestCase, MixinTests):
    def setUp(self):
        self.obj = Foo()

    def foo_specific_test(self):
        self.assertTrue(self.obj.something_else)


class BarTester(unittest.TestCase, MixinTests):
    def setUp(self):
        self.obj = Bar()

    def bar_specific_test(self):
        self.assertFalse(self.obj.something_else)

Make sure your MixinTests class doesn't subclass unittest.TestCase otherwise the test runner will try to run the tests in the mixin class itself.