1
我們使用PHPUnit過濾的方式非常廣泛,它似乎並不妨礙我們在不符合過濾條件的測試類中執行setUpBeforeClass()和tearDownAfterClass()結果。PHPUnit過濾不能與setUpBeforeClass()和tearDownAfterClass()一起使用
對於那些不知道,你可以使用--filter
選項來過濾PHPUnit測試。
像摩卡其他測試框架,除非它們匹配濾波器不執行燈具。
我們使用PHPUnit過濾的方式非常廣泛,它似乎並不妨礙我們在不符合過濾條件的測試類中執行setUpBeforeClass()和tearDownAfterClass()結果。PHPUnit過濾不能與setUpBeforeClass()和tearDownAfterClass()一起使用
對於那些不知道,你可以使用--filter
選項來過濾PHPUnit測試。
像摩卡其他測試框架,除非它們匹配濾波器不執行燈具。
我想要說的是我對所有的PHPUnit的貢獻者極大的尊重開始。
我們的解決方法是開發一種新的基類,提供一組新的,可用於代替setUpBeforeClass()和tearDownAfterClass()構建體。
class Test extends PHPUnit_Framework_TestCase {
/**
* PHPUnit has a serious design flaw where setUpBeforeClass() and tearDownAfterClass() are still
* executed for all test classes even if they don't match the filter. This appears to be due to
* PHPUnit applying the filter after these fixtures. Fortunately, with a little magic, we can
* define constructs for before() and after() that achieve our desired behavior. Some may say that
* this is not a PHPUnit bug, but other testing frameworks like mocha don't execute any of the
* fixtures unless the filters match.
*/
/**
* @var boolean True if we are executing this test
*/
protected static $executing = false;
/**
* Use instead of setUpBeforeClass() to create a fixture that is called once per test class and
* not called unless it is in the filter results.
*/
public static function before() {}
/**
* Use instead of tearDownAfterClass() to create a fixture that is called once per test class and
* not called unless it is in the filter results.
*/
public static function after() {}
/**
* A base method for setUp() that uses the $executing flag to determine whether or not to run
* before(). We cannot use setUpBeforeClass() here as setUpBeforeClass() will run before any
* filters are applied.
*/
protected function setUp() {
if (!self::$executing) {
static::$executing = true;
static::before();
}
}
/**
* A base method for tearDownAfterClass() that uses the $executing flag to determine whether or
* not to run after()
*/
public static function tearDownAfterClass() {
if (static::$executing) {
// Set to false so that this doesn't trigger execution of another classes fixtures as $executing
// is a static member
static::$executing = false;
static::after();
}
}
}
然後你可以在新的()之前和之後(使用)構造像這樣,他們將不會被執行,如果測試是不經過濾的結果的一部分:
class MyTest extends Test {
public static function before() {
// Code done once before all tests
}
public function testFoo() {
// Test something
}
public static function after() {
// Code done once after all tests
}
}
不是最佳解決方案曾經,但很高興它爲你工作。你碰巧知道它是PHPUnit中的錯誤還是未公開的特性? –