Courses

Advanced Laravel Testing

Arrange - Act - Assert: Multiple Times in One Method?

Previous: Create a Totally Custom Factory Class
avatar

Not linked to this video - not sure if i've missed it but i've seen in other frameworks like Mezzio people using functions that provided multidimensional arrays of invalid data e.g for an insert/update query where we test for incorrect or missing items in array that should return an exception of some type, what would be the best way to approach this in Laravel? (Apologies if the question isn't worded well)

e.g this test has a result factory, match_id must be an integer eg '123456789', however in the test I have purposely used the incorrect data type as I want to test the TypeError exception is called. However, rather than create a multiple versions of this function, how would I use some form of dataProvider to go through an array of incorrect arrays to pass into the create() function.

Hopefully that makes sense i'm still learning tests :)

    public function testErrorExceptionReturnedIfMatchIdValueIncorrect()
    {
        $this->expectException(\TypeError::class);
        Result::factory()->create([
            'match_id' => [],
        ]);
    }
avatar

I've had a look - not quite figured it out yet but it is something along these lines that I am trying to do - so the invalidData is an array that is passed to the first test and iterates through all the invalid data to check that the TypeError exception is expected. How do I amend the code below to do this, anyone got any ideas?

    /**
     * @test
     * @dataProvider invalidData
     */
    public function testErrorExceptionReturned($invalidData): void
    {
        $this->expectException(\TypeError::class);
        Result::factory()->create([
            $invalidData
        ]);
    }

    public function invalidData(): array
    {
        return [
            [
                'match_id' => []  // will fail must be an integer
            ],
            [
                'match_id' => 123456789,
                'home_team_id' => 'not-an-id'   // will fail must be an integer
            ]
        ];
    }
avatar
You can use Markdown
avatar
You can use Markdown