Laravel - PHPUnit - 模型工厂 - 多对多关系

时间:2017-12-08 10:17:57

标签: laravel-5 phpunit many-to-many factory

考虑以下内容

Students
Subjects
Exams

以及以下关系

Student belongsToMany Subjects (Many-to-Many)
Student hasMany Exams

Subject belongsToMany Students (Many-to-Many)
Subject hasMany Exams

Exam belongsTo Student
Exam belongsTo Subject

所以我正在使用ModelFactory为模型及其关系编写一些测试用例(我是单元测试的新手)。我需要测试一个考试的学生和科目相关的案例。所以我在测试和工厂中做了以下工作。

测试

public function testStudentAndSubjectIsRelated()
{
    $exam = factory(Exam::class)->create();

    // We need to know whether the student and subject is related

    $this->assertTrue($exam->student->subjects()->pluck('id')->contains($exam->student_id));

    // And viceversa
    $this->assertTrue($exam->subject->students()->pluck('id')->contains($exam->subject_id));
}

$factory->define(App\Exam::class, function (Faker\Generator $faker) {
    return [
        'student_id' => function () {
            return factory(App\Student::class)->create()->id;
        },
        'subject_id' => function ($exam) {
            $subject = factory(App\Subject::class)->create();

            $student = App\Student::find($exam['student_id']);

            $subject->students()->save($student);

            return $subject->id;
        },

        ....
    ];
});

这是正确的做法吗?

0 个答案:

没有答案