So with most unit testing utilities I have come across, you usually get access to a SetUp() and TearDown() function of some sort. While I see that this comes in very handy for almost every unit test, I was wondering how testing the initialization of objects should be handled? I mean, in almost every other test, you would just let the SetUp() function handle it. However, in most of the basic testing utilities I have worked with, SetUp() gets called before every test. I have been wondering if you just do the initialization testing within the SetUp() function, if one should make their own SetUp() equivalent function that gets called explicitly at the beginning of tests not related to initialization testing, or if there is some other generally accepted practice I have not brought up?
2 Answers
The initialization of an object is done by a constructor, so "testing initialization" means "testing the constructors". When testing a normal mutator method you would execute the method of interest, then make assertions about the state of the object afterwards. For a constructor it is just the same. The only difference from testing a normal method, if you create test fixtures in your setUp()
method, is that the test methods do not call the constructor themselves, but rely on the call in the set up method.
That said, I've moved away from the style of having the ThingTest
class that tests class Thing
have test fixtures of class Thing
. I instead create the objects of class Thing
directly in the test methods, using parameterised tests to reduce code duplication. I find this avoids the mystery guest code smell.

- 46,613
- 43
- 151
- 237
You may be overthinking this. Implementing setUp()
is optional, and any given test is free to ignore any state created by setUp()
. So you can either simply ignore that state for one test method that tests object initialization, or create a separate test class just for testing initialization which has an empty setUp()
method.

- 80,601
- 10
- 150
- 186