如果兩個或多個測試類(測試相同接口/抽象類的不同實現)具有不同固定裝置的共同測試但是,那麼重構測試用例是否是一個好主意?將常見測試重構爲基本測試用例
比方說,代碼和測試看起來像這樣:
interface MathOperation
{
public function doMath($a, $b);
}
class Sumator implements MathOperation
{
public function doMath($a, $b)
{
return $a + $b;
}
}
class Multiplicator implements MathOperation
{
public function doMath($a, $b)
{
return $a * $b;
}
}
// tests
class SumatorTest extends PHPUnit_Framework_TestCase
{
/**
* @var Sumator
*/
protected $sumator;
public function setUp()
{
$this->sumator = new Sumator;
}
/**
* @dataProvider fixtures
*/
public function testDoMath($a, $b, $expected)
{
$result = $this->sumator->doMath($a, $b);
$this->assertEqual($expected, $result);
}
public function fixtures()
{
return array(
array(1, 1, 2);
array(2, 1, 3);
array(100, -1, 99);
);
}
}
class MultiplicatorTest extends PHPUnit_Framework_TestCase
{
/**
* @var Multiplicator
*/
protected $multiplicator;
public function setUp()
{
$this->multiplicator = new Multiplicator;
}
/**
* @dataProvider fixtures
*/
public function testDoMath($a, $b, $expected)
{
$result = $this->multiplicator->doMath($a, $b);
$this->assertEqual($expected, $result);
}
public function fixtures()
{
return array(
array(1, 1, 1);
array(2, 1, 2);
array(100, -1, -100);
);
}
}
,我希望他們(測試)看起來像:
class MathOperationTestCase extends PHPUnit_Framework_TestCase
{
/**
* @var MathOperation
*/
protected $operation;
public function setUp()
{
$this->operation = $this->createImpl();
}
/**
* @return MathOperation
*/
abstract function createImpl();
/**
* @dataProvider fixtures
*/
public function testDoMath($a, $b, $expected)
{
$result = $this->operation->doMath($a, $b);
$this->assertEqual($expected, $result);
}
abstract public function fixtures();
}
class SumatorTest extends MathOperationTestCase
{
public function createImpl()
{
return new Sumator;
}
public function fixtures()
{
return array(
array(1, 1, 2);
array(2, 1, 3);
array(100, -1, 99);
);
}
}
class MultiplicatorTest extends MathOperationTestCase
{
public function createImpl()
{
return new Multiplicator;
}
public function fixtures()
{
return array(
array(1, 1, 1);
array(2, 1, 2);
array(100, -1, -100);
);
}
}
這似乎更好地組織,但可能缺乏可讀性。所以最後我不確定它是否可用。