Laravel 5 PHPUnit测试json帖子

时间:2016-04-07 18:05:29

标签: json api laravel testing phpunit

我正在尝试在officiel doc之后测试JSON API。我知道问题来自POST请求的数据数组。这个测试适用于像['hello' => 'world']这样的单级数组,所以显然post函数不能处理复杂的结构?我在这里做错了什么?

测试:

public function testInsert()
{
    $this->post(
        '/test',
        [
            'content' => 'Hello world!',
            'count' => [
                'a' => 12.345678,
                'b' => 12.345678
            ],
            'user' => [
                'id' => 1
            ]
        ],
        ['contentType' => 'application/json']
    )->seeJsonEquals([
        'status' => true
    ]);
}

错误:

unknown:myapp nobody$ phpunit
PHPUnit 4.8.24 by Sebastian Bergmann and contributors.

E.

Time: 648 ms, Memory: 15.25Mb

There was 1 error:

1) APITest::testInsert
ErrorException: Invalid argument supplied for foreach()

/Users/nobody/myapp/vendor/laravel/framework/src/Illuminate/Support/Arr.php:487
/Users/nobody/myapp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:231
/Users/nobody/myapp/tests/APITest.php:43

FAILURES!
Tests: 2, Assertions: 2, Errors: 1.

控制器:

public function store() {
    $user = User::find(Input::get('user.id'));

    // TODO: Validate input using JSON schema

    if (empty($user))
        $errors[] = 'User does not exist.';

    if (empty(Input::get('content')))
        $errors[] = 'Content is empty.';

    $a = Input::get('location.latitude');
    if ($a < 15)
        $errors[] = 'A out of range.';

    $b = Input::get('location.longitude');
    if ($b < 20)
        $errors[] = 'B out of range.';

    if (empty($errors)) {
        $post = new Post();

        $post->content = Input::get('content');
        $post->count()->create([
            'a' => $a,
            'b' => $b
        ]);

        $user->posts()->save($user);

        $post->save();

        return APIUtils::makeStatusResponse(true);
    }

    return APIUtils::makeStatusResponse(false, $errors);
}

1 个答案:

答案 0 :(得分:0)

我使用laravel new myapp命令重新安装了我的Laravel应用程序,现在一切正常。我假设问题来自之前使用composer create-project --prefer-dist laravel/laravel may进行的安装。