简体   繁体   English

PHPUnit + Laravel 5.2 +属性未正确返回

[英]PHPUnit + Laravel 5.2 + Attribute not returning properly

User.php - pretty vanilla hasMany relationship: User.php-漂亮的香草hasMany关系:

public function transactions()
{
    return $this->hasMany('App\Transaction');
}

UserTest.php: UserTest.php:

public function testTransactionsAttribute()
{
    $user = Auth::user();

    // Verify logged in user is expected user.
    $this->assertTrue($user->username == 'something');

    // Pay something.
    $transaction = $user->payMembershipFee();

    // Verify transaction is in database
    $this->seeInDatabase('transactions', ['amount' => 50, 'user_id' => $user->id]);

    // Verify transaction belongsTo relationship
    $this->assertTrue($transaction->user->username == 'something');

    // Verify user hasMany relationship - fails
    $this->assertTrue($user->transactions->count() > 0, 'The user should have at least one transaction associated.');
}

Here's where it gets interesting (I did not modify the database tables - just left PHPUnit and switched to Tinker): 这就是有趣的地方(我没有修改数据库表-刚离开PHPUnit并切换到Tinker):

$ php artisan tinker

Grab user (verified is same user created from test): 抓取用户(已验证是通过测试创建的同一用户):

$user = App\User::first()

Copy/Paste assertion: 复制/粘贴断言:

$user->transactions->count()
=> 1

Also, when I manually go through the steps locally - it works. 另外,当我在本地手动执行步骤时,它也可以工作。 So, it appears Laravel 5.2 is acting as expected. 因此,Laravel 5.2似乎按预期运行。 However, PHPUnit is not. 但是,PHPUnit不是。

I'm wondering if it's possible I'm missing something in the way Laravel 5.2 and PHPUnit work with one another? 我想知道是否有可能会丢失Laravel 5.2和PHPUnit相互配合的方式?

From outside the model (in the test itself, for example): 从模型外部(例如,在测试本身中):

$user = $user->fresh();

From inside the model one cannot do something like: 从模型内部,不能执行以下操作:

$this = $this->fresh();

So, inside the method that creates the Transaction for the User: 因此,在为用户创建事务的方法中:

public function createTransaction()
{
    $transaction = new Transaction;
    ...
    $transaction->save();

    // Refresh the relationship specifically        
    $this->load('transactions');

    // There is also fresh([])
    // which is supposed to be able to accept multiple relationships

    return $transaction;
}

https://laracasts.com/discuss/channels/testing/refresh-a-model https://laracasts.com/discuss/channels/testing/refresh-a-model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM