views:

24

answers:

3

I often need to set up the same test structures for different test cases. Therefore I created a TestService class that has several public methods for the test classes.

I guess that this is not the best place to put them as TestService will also be deployed although not needed on production.

Where would you put those commonly test methods? Is there a "best practice" for this?

A: 

Why don't you put it next to your test classes? The usual way is to put all test-related code into a directory separate from the source directory (e.g. "test"). I.e. not only the test cases themselves, but also supporting classes, such as utility methods, mock implementations etc.

The test cases should be put into the same package as the class tested by them (but in a different physical directory, as explained above). A test utility class which is used by several test cases should be put into some common utility package.

Péter Török
+1  A: 

I tend to try to keep to the DRY principle as much as I can when writing tests. This shows in mainly two ways:

  1. I usually implement a TestData class, that holds all the data I feed into my tests in static properties, to make it easier to keep track of what input I give the tests, and to make sure I never give different input when I intend to give the same. This resides in a test project, or in a class library referenced only by the test projects.

  2. If I find I need the same setup or teardown routines in many tests, I often make use of inheritance - create a base class that the test fixtures can inherit, where all the common actions go.

Footnote: I do almost all of my development in C#, but I believe these practices can be applied in any language with a testing framework.

Tomas Lycken
A: 

The way i do it is similar to the above answers. If I have a MyDomain class, I put a MyDomainTestHelper class in a test package. The helper has static methods on it that return the domain objects in question. So i might have a

static createTestMyDomain() {...}

that creates an instance with sensible defaults and

static createTestMyDomain(String something)

so I can specify something and so on.

You should not put them in a "service" as you mentioned. But any way you can be DRY is a good way.

hvgotcodes