【问题标题】:Testing a specific element using json POST in phpunit laravel-4在 phpunit laravel-4 中使用 json POST 测试特定元素
【发布时间】:2014-09-12 19:00:45
【问题描述】:

我正在尝试测试“名称”是否实际插入到我的控制器中。

我创建了这个测试来检查“名称”:

  public function testStoreName()
{
    $json = '{"name":"FOO", "address":"fubar City", "nickname":"fubar"}';
     $post = $this->action('POST', 'FooController@store', 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 并设置 "name": "";我得到错误。我想让它说“名称不能为空。

【问题讨论】:

    标签: php json laravel-4 phpunit


    【解决方案1】:

    试试这个:

       public function testStoreName()
           {
                $json = '{"name":"FOO", "address":"fubar City", "nickname":"fubar"}';
                $jsonDecode = json_decode($json, true);
                $name = $jsonDecode['name'];
                $post = $this->action('POST', 'FooController@store', 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'); 
    
            }
    

    上面的代码解码了 json 字符串,我们将 'name' 元素放入 $name,然后我们执行 assertEquals() 来比较我们指定的 json 字符串 'name' 和实际的 'name' 内容输入到控制器中。

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 2013-09-13
      • 2016-12-31
      • 1970-01-01
      • 2014-09-11
      • 2021-08-22
      • 2015-09-26
      • 2013-04-14
      • 2016-07-28
      相关资源
      最近更新 更多