在laravel-4中使用phpunit测试store()时未定义的变量


undefined variable when testing the store() using phpunit in laravel-4

已解决

我有一个路由,它向控制器中的store((执行POST路由。

我正在试着测试这个动作是否正常。

控制器:

public function store() {
    $d= Input::json()->all();
    //May need to check here if authorized
    $foo= new Foo;
    $d = array();
    $d['name'] = $d['name'];
    $d['address'] = $d['address'];
    $d['nickname'] = $d['nickname'];

    if($foo->validate($d))
    {
        $new_foo= $foo->create($d);
        return Response::json(Foo::where('id','=',$new_foo->id)->first(),200);
    }
    else
    {
        return Response::json($foo->errors(),400);
    }
}

现在我尝试使用一个名为FooTest.php 的新类来测试这一点

这是我目前试图做的功能,以使检查工作:

 public function testFooCreation()
{
    $jsonString = '{"address": "82828282", "email": "test@gmail.com", "name":"Tester"}';
    $json = json_decode($jsonString);
    $this->client->request('POST', 'foo');
    $this->assertEquals($json, $this->client->getResponse());
}

当我在cmd中运行phpunit时,我收到一个错误,指出"name"未定义。我知道我实际上并没有向请求传递任何东西,所以我确信实际上没有检查任何东西,但我的问题是,我如何真正传递json字符串进行检查?

每次我在客户端请求中放入$json时,它都会请求一个数组,但当我将json字符串转换为数组时,json_decode需要一个字符串。

更新

我在传递输入数据时遇到了这个问题:

 $input = [
        'name' => 'TESTNAME',
        'address' => '299 TESTville',
        'nickname' => 't'
        ];

     Input::replace($input);
     Auth::shouldReceive('attempt')
        ->with(array('name' => Input::get('name'),
                     'address' => Input::get('address'),
                     'nickname' => Input::get('nickname')))
        ->once()
        ->andReturn(true);

     $response = $this->call('POST', 'foo', $input);
     $content = $response->getContent();
     $data = json_decode($response->getContent());

但每当我运行测试时,我仍然会得到"名称:未定义",它仍然没有通过我创建的输入。

$d= Input::json()->all();

上面的语句获得$d中的Input。

$d = array();

现在,最后一条语句再次将$d初始化为空的新数组

所以没有:$[名字]。因此,未定义。

我认为,这就是上面代码的问题所在。

希望有帮助:(

我能够将测试中的输入传递到POST路由中。

 public function testFooCreation(){
      $json = '{"name":"Bar", "address":"FooLand", "nickname":"foobar"}';
      $post = $this->action('POST', 'FooController@store', null, array(), array(), array(), $json);
      if($this->assertTrue($this->client->getResponse()->isOk()) == true && $this->assertResponseStatus(201)){
      echo "Test passed";
      }
 }

事实证明,为了让我真正通过测试POST将输入传递到控制器,我必须通过第7个参数传递它。

我希望这能帮助其他人。

当然你会得到一个错误,只要看看你的代码

$aInputs=输入::json((->all((;//如果获得授权,可能需要在此处进行检查$foo=新foo;$d=array((;$d['name']=$d[`name'];$d[地址']=$d[住址'];$d['nickname']=$d['nickname']

您将数组分配给它自己,它是空的