我有一个客户端类,它使用魔术__call
方法来构造和端点类。
class Client
{
public function __call($name, $arguments)
{
$className = "\\App\\Endpoints\\" . ucfirst($name);
if (! class_exists($className)) {
throw new InvalidEndpointException("The `{$name}` endpoint was not configured.");
}
return new $className($this->getHttpClient());
}
// other methods
}
我的端点命名空间是App\Endpoints
。值得一提的是,我的所有端点都从一个包含所需逻辑的抽象Endpoint类扩展而来。端点本身几乎是空的,它们只包含端点url,或者在某些情况下还有一些非REST方法的其他方法。
现在我想测试魔术方法,并不是真的想要使用该命名空间中的真实端点,而是想编写我自己的测试双精度。为了做到这一点,我必须将ClientTest
类中的test double置于真正的命名空间App\Endpoints
下。此课程仅适用于此测试。
这就是我在ClientTest
课上的内容
namespace App\Tests;
class ClientTest extends TestCase
{
public function testItReturnsTheCorrectEndpointWhenCalled()
{
$resources = $this->client->myTestResources();
$this->assertInstanceOf(Endpoint::class, $resources);
}
}
namespace App\Endpoints;
class MyTestResources extends Endpoint
{
public static $endpoint = 'myTestResources';
}
有没有更好的方法来实现这一目标?
模拟可能是最好的方法。 There’s some notes about them in the PHPUnit docs,或者你可以参考你的框架(如果你正在使用它)。例如,Laravel,has a range of mocks。