0

I have a Symfony WebTestCase-extending PHP Test class and a DRY-trait. The test functions in my class @depend on the test functions in my trait, however I can't manage to execute the trait tests before the class tests. Is that possible?

trait TestTrait
{
    /**
     * @beforeClass
     */
    public function testBeforeAnythingElseHappens()
    {
        /*...*/
    }
    /* more functions */
}

Test Class

class Test extends WebTestCase
{
    use TestTrait;

    /**
     * @depends testBeforeAnythingElseHappens
     */
    function testClassSpecificStuff()
    {
        /* ... */
    }
}
localheinz
  • 9,179
  • 2
  • 33
  • 44
Leon Willens
  • 356
  • 1
  • 16
  • Make the trait-test-method return something. Add a parameter to the other test-method which will get the return value of the test it depends on. IIRC this enforces the dependency. See https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.test-dependencies – hakre Aug 08 '17 at 19:08

1 Answers1

1

First, see PHPUnit Manual - Appendix B. Annotations:

@beforeClass

The @beforeClass annotation can be used to specify static methods that should be called before any test methods in a test class are run to set up shared fixtures.

So, you should not use @beforeClass here - it is intended to allow setting up fixtures. In addition, the methods annotated as such should be static.

Second, see PHPUnit Manual - Appendix B. Annotations:

@depends

PHPUnit supports the declaration of explicit dependencies between test methods. Such dependencies do not define the order in which the test methods are to be executed but they allow the returning of an instance of the test fixture by a producer and passing it to the dependent consumers.

So yes, you could use the @depends annotation to declare dependencies between tests. Just remove the @beforeClass annotation:

trait TestTrait
{
    public function testBeforeAnythingElseHappens()
    {
    }
}

class Test extends WebTestCase
{
    use TestTrait;

    /**
     * @depends testBeforeAnythingElseHappens
     */
    public function testClassSpecificStuff()
    {
    }
}

Third, a few words of advice (from my own experience):

  • Do not require tests to be run in a certain order.
  • If you arrange something in one test and need the same thing in another, just do it multiple times, do not worry too much about repeating yourself.

For reference, see:

localheinz
  • 9,179
  • 2
  • 33
  • 44