How to catch PHP Warning in PHPUnit

后端 未结 6 1041
迷失自我
迷失自我 2021-01-01 15:47

I am writing test cases and here is a question I have.

So say I am testing a simple function someClass::loadValue($value)

The normal test case

6条回答
  •  太阳男子
    2021-01-01 16:02

    I would create a separate case to test when the notice/warning is expected.

    For PHPUnit v6.0+ this is the up to date syntax:

    use PHPUnit\Framework\Error\Notice;
    use PHPUnit\Framework\Error\Warning;
    use PHPUnit\Framework\TestCase;
    
    class YourShinyNoticeTest extends TestCase
    {
    
        public function test_it_emits_a_warning()
        {
            $this->expectException(Warning::class);
    
            file_get_contents('/nonexistent_file'); // This will emit a PHP Warning, so test passes
        }
    
    
        public function test_it_emits_a_notice()
        {
            $this->expectException(Notice::class);
    
            $now = new \DateTime();
            $now->whatever; // Notice gets emitted here, so the test will pass
        }
    }
    

提交回复
热议问题