2014-09-23 23 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