我用PHP对我用Symfony2编写的控制器做了一个小测试:
class DepositControllerTest extends WebTestCase {
public function testDepositSucceeds() {
$this->crawler = self::$client->request(
'POST',
'/deposit',
array( "amount" => 23),
array(),
array()
);
$this->assertEquals(
"Deposit Confirmation",
$this->crawler->filter("title")->text());
}
}
到这里为止,一切都很棒。当我意识到我想在刷新页面时禁用可能的重新提交时,问题就开始了。所以我添加了一个小机制,在每次提交时发送随机数。
它的工作原理是这样的:
class ReplayManager {
public function getNonce() {
$uid = $this->getRandomUID();
$this->session->set("nonce", $uid);
return $uid;
}
public function checkNonce($cnonce) {
$nonce = $this->session->get("nonce");
if ($cnonce !== $nonce)
return false;
$this->session->set("nonce", null);
return true;
}
}
所以我不得不修改控制器,以便在显示表单时获取随机数,并在提交时使用它。
但现在这带来了一个问题。我无法向POST /deposit
提出请求,因为我不知道要发送什么随机数。我想首先请求GET /deposit
来渲染表单,并设置一个,以便在POST
中使用它,但我怀疑 Symfony2 会话在 PHPUnit 中不起作用。
我该如何解决这个问题?我不想去硒测试,因为它们明显慢,更不用说我将不得不重写很多测试。
更新:我根据请求添加了一个非常简化的控制器代码版本。
class DepositController extends Controller{
public function formAction(Request $request){
$this->replayManager = $this->getReplayManager();
$context["nonce"] = $this->replayManager->getNonce();
return $this->renderTemplate("form.twig", $context);
}
protected function depositAction(){
$this->replayManager = $this->getReplayManager();
$nonce = $_POST["nonce"];
if (!$this->replayManager->checkNonce($nonce))
return $this->renderErrorTemplate("Nonce expired!");
deposit($_POST["amount"]);
return $this->renderTemplate('confirmation.twig');
}
protected function getSession() {
$session = $this->get('session');
$session->start();
return $session;
}
protected function getReplayManager() {
return new ReplayManager($this->getSession());
}
}
我不确定 ReplayManager 是做什么的,但在我看来,它似乎不是处理"随机数"的正确类。由于"nonce"最终存储在会话中并从会话中检索,因此它应该由控制器处理或抽象到自己的类中,然后作为依赖项传入。这将允许您模拟随机数(听起来像情景喜剧!)进行测试。
根据我的经验,测试中的问题实际上是代码设计的问题,应该被认为是一种气味。在这种情况下,您的问题源于在错误的位置处理随机数。快速重构会话应该可以解决您的测试问题。
可以通过
WebTestCase客户端从PHPUnit访问Symfony2会话。我认为这样的事情应该有效:
public function testDepositSucceeds() {
$this->crawler = self::$client->request(
'GET',
'/deposit',
);
$session = $this->client->getContainer()->get('session');
$nonce = $session->get('nonce');
$this->crawler = self::$client->request(
'POST',
'/deposit',
array("amount" => 23, "nonce" => $nonce),
array(),
array()
);
$this->assertEquals(
"Deposit Confirmation",
$this->crawler->filter("title")->text());
}
编辑:
或者,如果从会话中获取随机数值时出现问题,您可以尝试将上述 GET 和 POST 请求之间的两行替换为:
$form = $crawler->selectButton('submit');
$nonce = $form->get('nonce')->getValue(); // replace 'nonce' with the actual name of the element