Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: Get name of test class and method from setUp()?

Tags:

php

phpunit

PHPUnit runs the setUp() method of a test class prior to running a specific test.

I load up test-specific fixtures for every test in a test class and would prefer not to have to explicitly do so. I would ideally like to handle this automagically in the setUp() method.

If the setUp() method makes available the test class name and test method name this can be done.

Is the name of the test class and method that is about to be run available to me in the setUp() method?

like image 734
Jon Cram Avatar asked Oct 03 '12 07:10

Jon Cram


1 Answers

The easiest way to achieve this should be calling $this->getName() in setUp().

<?php

class MyTest extends PHPUnit_Framework_TestCase
{
    public function setUp() {
        var_dump($this->getName());
    }


    public function testMethod()
    {
        $this->assertEquals(4,2+2,'OK1');
    }
}

And running:

phpunit MyTest.php 

produces:

PHPUnit 3.7.1 by Sebastian Bergmann.

.string(10) "testMethod"


Time: 0 seconds, Memory: 5.00Mb

OK (1 test, 1 assertion)

In general I'd advice against doing this but there sure are cases where it can be a nice way to do things.

Other options would be to have more than one test class and having all the tests that use the same fixtures together in one class.

Another would be to have private setUp helpers and calling the appropriate one from the test case.

like image 123
edorian Avatar answered Sep 28 '22 06:09

edorian