使用Zend_Session_Namespace进行单元测试

时间:2012-10-01 03:39:50

标签: php unit-testing zend-framework session phpunit

我正在为登录系统编写单元测试 - 但是在与Zend_Session_Namespace对象进行交互时遇到了困难。我正在使用PHPUnit框架的Zend_Test扩展(ZF 1.10,PHPUnit 3.4.5)

测试

public function testAuthFailure()
{
  $request = $this->getRequest();
  $request->setMethod("POST");
  $request->setPost("username", "testUser");
  $request->setPost("password", "testPassword");

  $this->dispatch("/auth/login");

  $this->assertModule("auth");
  $this->assertController("login");
  $this->assertAction("validate");

  $loginSession = new Zend_Session_Namespace("login");
  $this->assertFalse(is_null($loginSession));
  $this->assertObjectHasAttribute("messages", $loginSession);
  $this->assertFalse(empty($loginSession->messages));
  $this->arrayHasKey("error", $loginSession->messages["error"]);
  $this->assertEquals($loginSession->messages["error"], "Could not log you in with that username and/or password");
}

当前控制器/操作代码

public function validateAction()
{
  $loginSession = new Zend_Session_Namespace("login");

  if (!$this->buildForm()->isValid($this->getRequest()->getPost())) {
    $loginSession->messages["error"][] = "Please enter your username and password";
  }

  $loginSession->messages["error"][] = "Could not contact the authentication server";

  $this->getResponse()
    ->setHttpResponseCode(303)
    ->setHeader("Location", "/auth/login");
}

我的单元测试在$this->assertObjectHasAttribute("messages", $loginSession);失败 - 但我希望它在消息的实际内容上失败。

我的phpunit bootstrap中有这些行:

Zend_Session::$_unitTestEnabled = true;
Zend_Session::start();

如何确认会话消息设置正确?

1 个答案:

答案 0 :(得分:0)

今天在重新审视这个问题时,有一个完整的面孔时刻:

我的Zend_Session_Namespace上的“message”属性实际上是一个魔术属性(使用__get和__set访问),并且无法通过反射识别(这是PHPUnit在调用assertObjectHasAttribute时测试属性是否存在的方式)。 / p>

从测试中删除断言允许它继续,我的测试现在在预期的点上失败而不是过早。

相关问题