2014-07-22 36 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字符串“名称”。