gpt4 book ai didi

php - 如何在 PHP 中为接口(interface)编写测试

转载 作者:行者123 更新时间:2023-11-28 21:04:47 25 4
gpt4 key购买 nike

如果我正在编写一个接口(interface),我通常会指定实现应该公开的行为。为了确保这种行为,应该针对这个接口(interface)编写测试。我如何最好地编写和组织这些测试,以便实现的编写者可以轻松地使用它们来确保它们的实现满足要求?是通过某种方式扩展(编写子类)接口(interface)来测试要走的路还是实现某种设计模式(如工厂)?

最佳答案

我明白为什么人们告诉您您不需要测试接口(interface)。但这不是你要问的。您正在寻求一种更简单的方法来对实现特定接口(interface)的多个类执行相同的单元测试。我使用 @dataProvider 来做到这一点注释(PHPUnit,是的)。

假设您有这些类:

interface Shape {
public function getNumberOfSides();
}

class Triangle implements Shape {
private $sides = 3;

public function getNumberOfSides() {
return $this->sides;
}
}

class Square implements Shape {
private $sides = 4;

public function getNumberOfSides() {
return $this->sides;
}
}

现在您要测试 Triangle 的实例是否定义了 getNumberOfSides 并返回 3,而对于 Square 则返回 4 .这是您使用 @dataProvider 编写此测试的方式:

class ShapeTest extends PHPUnit_Framework_TestCase {

/**
* @dataProvider numberOfSidesDataProvider
*/
public function testNumberOfSides(Shape $shape, $expectedSides){
$this->assertEquals($shape->getNumberOfSides(), $expectedSides);
}

public function numberOfSidesDataProvider() {
return array(
array(new Square(), 5),
array(new Triangle(), 3)
);
}
}

在这里运行 phpunit 会产生预期的输出:

There was 1 failure:

1) ShapeTest::testNumberOfSides with data set #0 (Square Object (...), 5)
Failed asserting that 5 matches expected 4.

/tests/ShapeTest.php:12

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

关于php - 如何在 PHP 中为接口(interface)编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29164814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com