【发布时间】:2015-12-26 18:37:35
【问题描述】:
过去我总是偶然发现 phpspec 的某个问题:
假设我有一个方法可以调用另一个对象的多个方法
class Caller {
public function call(){
$this->receiver->method1();
...
$this->receiver->method2();
}
}
在 BDD 中,我首先会编写一个测试,以确保调用 method1。
function it_calls_method1_of_receiver(Receiver $receiver){
$receiver->method1()->shouldBeCalled();
$this->call();
}
然后我会编写下一个测试以确保将调用 method2。
function it_calls_method2_of_receiver(Receiver $receiver){
$receiver->method2()->shouldBeCalled();
$this->call();
}
但是这个测试在 phpspec 中失败了,因为 method1 在 method2 之前被调用。 为了满足 phpspec,我必须检查两个方法调用。
function it_calls_method2_of_receiver(Receiver $receiver){
$receiver->method1()->shouldBeCalled();
$receiver->method2()->shouldBeCalled();
$this->call();
}
我的问题是,每次测试都会膨胀。在这个例子中,它只是一个额外的行,但想象一个方法,它用很多 setter 构建一个对象。 我需要为每个测试编写所有设置器。很难看出测试的目的,因为每个测试都很大并且看起来都一样。
我很确定这不是 phpspec 或 bdd 的问题,而是我的架构的问题。写这个更好(更可测试)的方法是什么?
例如:
public function handleRequest($request, $endpoint){
$endpoint->setRequest($request);
$endpoint->validate();
$endpoint->handle();
}
在这里,我验证请求是否为特定端点提供了所有必要的信息(或抛出异常),然后处理该请求。我选择这种模式来将验证与端点逻辑分开。
【问题讨论】: