如何编写Zend framework 2 cookie的测试用例?

时间:2014-09-23 12:30:30

标签: php zend-framework cookies zend-framework2 phpunit

我编写了实用程序类,用于读写cookie。我没有想法为我的实用程序类编写测试用例。

如何使用Zend framework 2 Http / Client编写测试用例? 这是否必须测试此实用程序类? (因为它使用默认的zend框架方法)

class Utility
{
  public function read($request, $key){//code}

  public function write($reponse, $name, $value)
  {
   $path = '/';
   $expires = 100;
   $cookie = new SetCookie($name,$value, $expires, $path);
   $response->getHeaders()->addHeader($cookie);
  }
}

- 提前致谢

1 个答案:

答案 0 :(得分:1)

是的:如果您依赖这条逻辑,我会测试这段代码。重要的是要知道在调用此方法时,cookie总是使用给定的值设置。

一种了解如何测试这篇文章的方法是使用SlmLocale中的一个示例:一个ZF2语言环境检测模块,可能将语言环境写入cookie。您可以找到代码in the tests

在你的情况下:

use My\App\Utility;
use Zend\Http\Response;

public function setUp()
{
    $this->utility  = new Utility;
    $this->response = new Response;
}
public function testCookieIsSet()
{
    $this->utility->write($this->response, 'foo', 'bar');

    $headers = $this->response->getHeaders();
    $this->assertTrue($headers->has('Set-Cookie'));
}

public function testCookieHeaderContainsName()
{
    $this->utility->write($this->response, 'foo', 'bar');

    $headers = $this->response->getHeaders();
    $cookie  = $headers->get('Set-Cookie');
    $this->assertEquals('foo', $cookie->getName());
}

public function testCookieHeaderContainsValue()
{
    $this->utility->write($this->response, 'foo', 'bar');

    $headers = $this->response->getHeaders();
    $cookie  = $headers->get('Set-Cookie');
    $this->assertEquals('bar', $cookie->getValue());
}

public function testUtilitySetsDefaultPath()
{
    $this->utility->write($this->response, 'foo', 'bar');

    $headers = $this->response->getHeaders();
    $cookie  = $headers->get('Set-Cookie');
    $this->assertEquals('/', $cookie->getPath());
}

public function testUtilitySetsDefaultExpires()
{
    $this->utility->write($this->response, 'foo', 'bar');

    $headers = $this->response->getHeaders();
    $cookie  = $headers->get('Set-Cookie');
    $this->assertEquals(100, $cookie->getExpires());
}