简体   繁体   中英

PHPUnit setUp to run for an individual test with dataProvider

I have a PHPUnit test testFoo() with a dataProvider fooProvider() . At the beginning of testFoo() I'm using Runkit to redefine a method so I can test expected results when that method is returning what I've redefined it to return. However, redefining the method is a little time-intensive, so I'd like for it to only happen once for this test.

Does the PHPUnit framework provide functionality to specify code that I'd like to run just once before testFoo() runs and not once for each element returned by fooProvider() or once per test in the suite (as with setUp() )?

Use a static private property to flag that the method has been redefined. You need it to be static because the test class is instantiated for each case provided by the dataProvider.

class FooTest extends PHPUnit_Framework_TestCase
{
    private static $redefined = false;

    /**
     * @dataProvider fooProvider
     */
    public function testFoo()
    {
        if (! self::$redefined) {

            // redefinition code goes here

            self::$redefined = true;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM