简体   繁体   中英

How to write testcases for Zend framework 2 cookies?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM