2014-09-23 95 views
0

我已经写了要读取和写入cookie的实用类。我没有想法为我的实用程序类编写测试用例。如何为Zend framework 2 cookies编写测试用例?

我怎样才能通过使用Zend Framework 2 HTTP /客户编写测试用例?
测试此实用程序类是强制性的吗? (因为它使用默认的Zend Framework的方法)

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提前

回答

1

是:如果依靠这片逻辑的我会测试该代码。当您调用此方法时,知道cookie始终设置为给定值很重要。

一个办法看你如何测试片是从SlmLocale一个例子:写入可能的语言环境下来到一个cookie一个ZF2区域检测模块。你可以找到代码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()); 
} 
+0

优秀的解决方案!你能帮我写一个针对'$ this-> utility-> read($ request,$ key)'的测试用例吗? – 2014-09-24 12:20:38

+0

在上面的代码,请使用'$饼干= $包头中>的get( '设置Cookie')[0];''而不是饼干$ = $包头中>的get( '设置Cookie');' – 2014-09-24 12:21:50

+0

你是对,你必须取得它的第一个价值。对于其他测试,请查看我提供的链接。该文件中的testLocaleInCookieIsReturned方法用于测试读取cookie值。 – 2014-09-24 16:20:41

相关问题