2014-07-22 64 views
2

我試圖測試一個「名稱」是否實際插入到我的控制器中。在phpunit中使用json POST測試特定元素laravel-4

我創造了這個測試來檢查的「姓名」:

public function testStoreName() 
{ 
    $json = '{"name":"FOO", "address":"fubar City", "nickname":"fubar"}'; 
    $post = $this->action('POST', '[email protected]', null, array(), array(), array(), $json); 
    $output= json_decode($this->client->getResponse()->getContent()); 
    $output->name; 



    if($output->name != "") 
    { 
     echo "Test Passed\n\n"; 
    } 

    elseif($output->name == "") 
    { 
     echo "Name cannot be null"; 
    } 

    //  $this->assertTrue($this->client->getResponse()->isOk()); 
} 

但是,當我改變$ JSON和設置「名稱」:「」;我收到錯誤。我想不必多說,「名字不能爲空

回答

1

試試這個:

public function testStoreName() 
     { 
      $json = '{"name":"FOO", "address":"fubar City", "nickname":"fubar"}'; 
      $jsonDecode = json_decode($json, true); 
      $name = $jsonDecode['name']; 
      $post = $this->action('POST', '[email protected]', null, array(), array(), array(), $json); 

      $this->assertTrue($this->client->getResponse()->isOk()); 

      $output= json_decode($this->client->getResponse()->getContent()); 

      $this->assertEquals($name, $output->name, 'Name incorrect'); 

     } 

上面的代碼decoes JSON字符串,我們把‘名’元素爲$name,我們做一個assertEquals()比較我們爲輸入到控制器的實際「名稱」內容指定的json字符串「名稱」。