Non-test methods in a Python TestCase

PythonUnit Testing

Python Problem Overview


Ok, as Google search isn't helping me in a while (even when using the correct keywords).

I have a class extending from TestCase in which I want to have some auxiliary methods that are not going to be executed as part of the test, they'll be used to generate some mocked objects, etc, auxiliary things for almost any test.

I know I could use the @skip decorator so unittest doesn't run a particular test method, but I think that's an ugly hack to use for my purpose, any tips?

Thanks in advance, community :D

Python Solutions


Solution 1 - Python

I believe that you don't have to do anything. Your helper methods should just not start with test_.

Solution 2 - Python

The only methods that unittest will execute [1] are setUp, anything that starts with test, and tearDown [2], in that order. You can make helper methods and call them anything except for those three things, and they will not be executed by unittest.

You can think of setUp as __init__: if you're generating mock objects that are used by multiple tests, create them in setUp.

def setUp(self):
    self.mock_obj = MockObj()

[1]: This is not entirely true, but these are the main 3 groups of methods that you can concentrate on when writing tests.

[2]: For legacy reasons, unittest will execute both test_foo and testFoo, but test_foo is the preferred style these days. setUp and tearDown should appear as such.

Solution 3 - Python

The test runner will only directly execute methods beginning with test, so just make sure your helper methods' names don't begin with test.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvictorcamposView Question on Stackoverflow
Solution 1 - PythonJ LundbergView Answer on Stackoverflow
Solution 2 - PythonBrian RileyView Answer on Stackoverflow
Solution 3 - PythonMark CidadeView Answer on Stackoverflow