views:

766

answers:

8

Is there a way to get the tests inside of a TestCase to run in a certain order? For example, I want to seperate the lifecycle of an object from creation to use to destruction but need to make sure that the object is set up first before I run the other tests.

+9  A: 

Maybe there is a design problem in your tests.

Usually each test must not depend on any other tests, so they can run in any order.

Each test needs to instantiate and destroy everything it needs to run, that would be the perfect approach, you should never share objects and states between tests.

Can you be more specific about why you need the same object for N tests?

Fabio Gomes
A: 

I was converting some old tests that were designed outside of PHPUnit and was just moving the functions over. You're right, there isn't any need to use multiple functions. Consider it a brain fart :P

dragonmantank
A: 

There really is a problem with your tests if they need to run in a certain order. Each test should be totally independent of the others: it helps you with defect localization, and allows you to get repeatable (and therefore debuggable) results.

Checkout this site for a whole load of ideas / information, about how to factor your tests in a manner where you avoid these kinds of issues.

jkp
Which site? Also, PHPUnit supports test dependencies via @depends.
mjs
A: 

Checkout this site for a whole load of ideas / information, about how to factor your tests in a manner where you avoid these kinds of issues.

Did you mean StackOverflow or another site?

dragonmantank
+2  A: 

If you want your tests to share various helper objects and settings, you can use setUp(), tearDown() to add to the sharedFixture property.

Gary Richardson
+3  A: 

PHPUnit supports test dependencies via the @depends annotation.

mjs
A: 

PHPUnit allows the use of '@depends' annotation which specifies dependent test cases and allows passing arguments between dependent test cases.

saleem badreddine
A: 

In my view, take the following scenario where I need to test creation and destroying of a particular resource.

Initially I had two methods, a. testCreateResource and b. testDestroyResource

a. testCreateResource

<?php
$app->createResource('resource');
$this->assertTrue($app->hasResource('resource'));
?>

b. testDestroyResource

<?php
$app->destroyResource('resource');
$this->assertFalse($app->hasResource('resource'));
?>

I think this is a bad idea, as testDestroyResource depends upon testCreateResource. And a better practice would be to do

a. testCreateResource

<?php
$app->createResource('resource');
$this->assertTrue($app->hasResource('resource'));
$app->deleteResource('resource');
?>

b. testDestroyResource

<?php
$app->createResource('resource');
$app->destroyResource('resource');
$this->assertFalse($app->hasResource('resource'));
?>
bibstha