How to test multiple PHP TypeErrors in one test?

I have following method:

MyClass {
   public function __construct(array $data, ?SomeObject $object): void
}

I have following test:

public function testWrongDataTypeThrowsErrorException(): void
{
    $this->expectException(TypeError::class);

    //works as expected
    new MyClass(null, new SomeObject);
    
    //this is never called
    new MyClass('string', new SomeObject);
}

And what happens is it only runs 1 test/assertion with the null parameter. The second time when I try to create MyClass with string, it never gets there. Why is that?

The same logic works if the code throws regular Exception.

I can write 2 separate methods instead, but thats very inconvenient.

Or is it stupid to test for this? My idea is that I want to test that the method accept array and only array. So if somebody would remove it from the method the test would fail.



Read more here: https://stackoverflow.com/questions/68411900/how-to-test-multiple-php-typeerrors-in-one-test

Content Attribution

This content was originally published by Honza at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: