How do I test for an exact Exception message, rather than a substring, with PHPUnit?

后端 未结 6 1768
难免孤独
难免孤独 2021-01-12 07:14

According to the PHPUnit Documentation on @expectedExceptionMessage, the string must only be a substring of the actual Exception thrown.

In

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 07:34

    I tried many ways to test exceptions and finally I found that the best way to test Exceptions is try-catch blocks. I suggest you to throw exceptions with exception code and then test if exception with this code is thrown. For example suppose that your exception code is 101

    if(count($errors) > 0) throw new \Exception(trim(implode(" ", $errors)), 101);
    

    For example suppose that your exception code is 101

    try {
        $myClass->validate(1, 2, 4, 3);
        $this->fail( "Exception with 101 code should be thrown" );
    } catch (Exception $e) {
        $this->assertEquals( 101, $e->getCode());
    }
    

提交回复
热议问题