'PHPUnit 7: Failed asserting that exception of type \InvalidArgumentException is thrown

I have this code:

public function method(){
  //...
  if(!$exist) {
      throw new \InvalidArgumentException('Ce client inexistant', 400);
  }
}

I do the UT of this code:

public function methodTest(){
      //...
      if(!$exist) {
          $this->expectExceptionMessage("Ce client inexistant");
          $this->expectException("\InvalidArgumentException");
      }
    }

It displays an error message

Failed asserting that exception of type "\InvalidArgumentException" is thrown.

I don't know where is the error in my code.



Solution 1:[1]

I solve my problem. This is the code:

$this->throwException(new \InvalidArgumentException('Ce client inexistant', 400));

Solution 2:[2]

For those who faced this issue, try this:

    $this->expectException(Exception::class);

    $client = self::createClient();
    $client->catchExceptions(false);

    $client->request(...);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 H Aßdøµ
Solution 2 Eduard Bulava