【问题标题】:How to write testcases for Zend framework 2 cookies?如何为 Zend 框架 2 cookie 编写测试用例?
【发布时间】:2014-11-17 15:57:31
【问题描述】:

我已经编写了用于读取和写入 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);
  }
}

--提前致谢

【问题讨论】:

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


    【解决方案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());
    }
    

    【讨论】:

    • 优秀的解决方案!你能帮我写一个针对$this->utility->read($request, $key)的测试用例吗?
    • 在上面的代码中请使用$cookie = $headers->get('Set-Cookie')[0];而不是$cookie = $headers->get('Set-Cookie');
    • 你是对的,你必须获取它的第一个值。对于其他测试,请查看我提供的链接。该文件中的 testLocaleInCookieIsReturned 方法用于测试读取 cookie 值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2022-01-19
    • 2014-08-02
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多