tags:

views:

48

answers:

3

My test fixtures often have "setup" member functions that cannot be called during construction of the fixture since they have parameters that will change based on the tests that will be run. They are written to avoid code duplication.

Are these functions creating an invalid test because they rely on complex, non-production means of being setup? Is their existence an indication that my class is poorly designed and difficult to construct? Should these methods be provided to my tests by the class I'm testing myself?

+1  A: 

It may just mean that you need to parameterize the construction with different parameters to test different permutations, in which case I think its 100% legit. DRY applies just as much within tests as within code.

Different test construction scenarios may be an indication that your class is not following the single responsibility principle. You can have several different construction methods because you need to construct the class in several different states Significantly different construction probably means mixed responsibilities of test subject.

krosenvold
A: 

Each test should be testing a certain kind of functionality for a certain function. So it's okay if the setup is not production standard, as long as the purpose of the test is the production usage.

So if you're creating a Add(int a, int b) test, it doesn't matter if int a and int b are generated in the way that you would do it exactly on the production environment as long as Add gives the correct response.

You should ALSO create a test for the generation of your "int a" and "int b" so that you know when THEY are created they will be the expected objects.

I hope that was clear. If not, I'll edit.

A: 

If you have different setup for each test perhaps you need to run the setup inside the needed test. Having a lot of code inside your setup could suggest that you are using integration test and not unit tests. Using mock objects could reduce your test setup logic considerably.

Unit tests should have single responsiblity and be easy to understand and maintain and I think that a parametrized setup might hurt this cause.

Dror Helper