0

我正在对一对多关系进行功能测试。我只是与基于 Laravel 文档的正确设置建立了简单的一对多关系。我的测试是这样的。

   /** @test */
    public function it_attach_containers()
    {
        $this->withoutExceptionHandling();

        $vendor = factory(Vendor::class)->create();

        $containersCount = 30;
        $containers = factory(Container::class, $containersCount)->create();

        $user = factory(User::class)->create();

        $attributes = [
            'vendor' => $vendor->id,
            'ordered' => null,
            'deployed' => null,
            'last_contact' => null,
            'containers' => $containers->pluck('name')
        ];

        $response = $this->actingAs($user, 'api')
            ->withHeaders([
                'X-Requested-With' => 'XMLHttpRequest'
            ])
            ->json('POST', '/api/deployments', $attributes);

        $deployment = Deployment::find($containers[0]->id);

        $this->assertInstanceOf(Deployment::class, $deployment);

        $this->assertCount($containersCount, $deployment->containers()->get());

        $this->assertDatabaseHas('deployments', [
            'vendor' => $vendor->id,
            'ordered' => null,
            'deployed' => null,
            'last_contact' => null
        ]); 
    }

我的关系是一对多的关系。一个部署有多个容器。下面的代码是我如何关联关系..


    public function associateDeployment(Deployment $deployment, $data)
    {
        foreach ($data['containers'] as $containerName) {
            $container = Container::where('name', $containerName)->first();
            if (!$container) {
                $container = Container::create([
                    'name' => $containerName,
                    'status' => true
                ]);
            }

            if (is_null($container->deployment_id)) {
                $container->deployment()->associate($deployment);
                $container->save();
            }            
        }
    }

我的测试结果真的很奇怪。有时它会通过,但有时不会。我注意到问题发生在assertCount. 正如你在我的测试中看到的那样。它断言容器是否为 30。但大多数情况下它没有达到 30。它大约是 25-29 ..然后有时它会通过。你认为是什么问题?

4

1 回答 1

0

我认为错误是以下行:

$deployment = Deployment::find($containers[0]->id);

在这里,您正在使用容器 ID 获取部署记录。而是使用以下代码:

$deployment = Deployment::find($containers[0]->deployment_id);
于 2020-03-13T15:48:43.567 回答