Question

Say I have a class that uses parameters in constructor, as such:

$var = new MyClass(1, 2, 3);

and my various tests depend on the parameters being passed to the class.

I have noticed that PHPUnit has setUp() and tearDown() methods, which can be used to instantiate a class, usually when constructor has no parameters, before execution of each test.

Is there a way to use setUp and tearDown methods in my test harness for such classes as in my example, or do I just instead instnatiate my classes individually in each test, as I have been doing?

I am asking this question more so to check that I have not missed anything on how to use setUp and tearDown properly.

Was it helpful?

Solution

I agree with inf3rno's answer: you should not use setUp if the constructor needs parameters.

Maybe you can get advantage of another feature: dataProviders. They allow you to define multiple data sets for the same test:

public function sumExamples()
{
    return array(
       array(1, 2, 3),
       array(1, -1, 0),
       array(-1, -2, -3)
    );
}

/**
 * @dataProvider sumExamples
 */
public function testSum($a, $b, $expected_result)
{
    $instance = new Sum(1, 2);
    $this->assertEquals($expected_result, $sum->getValue());
}

PHPUnit docs on this

This technique is useful only when the assertions are the same for all the data sets, of course.

Finally, if the constructor parameters are mandatory for the object to work, I'd keep them where they are. Getting rid of them just so you can instantiate the object at setUp is not correct IMO.

OTHER TIPS

and my various tests depend on the parameters being passed to the class.

If the test is depending on the constructor parameters, you cannot use setUp to create the instances... Setup is for repetitive things... Try to avoid constructor injection if possible, so you can use something like this:

protected $instance;
public function setUp(){
    $this->instance = new MyClass();
}

public function testSomething(){
    $this->instance->setParams(1,2,3);
    //...
    $this->assertEquals(...);
}

public function testSomethingElse(){
    $this->instance->setFirstParam(1);
    $this->instance->setSecondParam(2);
    $this->instance->setThirdParam(3);
    //...
    $this->assertEquals(...);
}

Ofc. this depends on what your Class does...

The two methods setUp and tearDown are mostly by convention. You can make use of them if you need to, but you must not.

E.g. it can be perfectly fine that you have a private helper method that helps you to create instances of the subject under test. You could also use setUp to create a factory for those. Do what helps you keeping the code of the tests small and dead simple.

As you have not shared any of your test-code, I can not give a more specific suggestion.

Read on: xUnit (Wikipedia) and Implicit Setup (xUnit Pattern).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top