dongqu2863
dongqu2863
2014-09-23 12:30

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

已采纳

I have written the utility class which going to read and write cookies. I don't have an idea to write the test cases for my utility class.

How can i write test cases by using Zend framework 2 Http/Client?
Is this mandatory to test this utility class? (since it uses default zend framework methods)

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);
  }
}

--Thanks in advance

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanfei1975 duanfei1975 7年前

    Yes: if you rely on this piece of logic I would test this code. It is important to know that the cookie is always set with the given values when you call this method.

    A way to look how you can test the piece is with an example from SlmLocale: a ZF2 locale detection module that writes possibly the locale down into a cookie. You can find the code in the tests.

    In your case:

    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());
    }
    
    点赞 评论 复制链接分享

相关推荐