How to unit test Exceptions with PHPUnit?

后端 未结 2 1483
刺人心
刺人心 2020-12-15 22:59

I\'m not getting how to unit test Exceptions with PHPUnit.

Please see my method with the Exception:

    public function getPhone($html, $tag = \'OFF         


        
2条回答
  •  孤城傲影
    2020-12-15 23:24

    You are doing too much there.

    Either use: @expectedException Exception

    OR: try / catch / $this->fail

    The way you are doing it right now says "catch that exception and THEN expect the code to throw another one!"

    The first way is cleaner in my opinion because it's only 1 line against 5 (or even more) lines of code and it's less error prone.

    /**
    * @covers Scrap::getPhone
    * @expectedException Exception
    *
    */
    public function testGetPhone() {
    
        // Variables1
        $array_static1 = Array(0 => 218559372, 1 => 927555929, 2 => 213456789, 3 => 912345678);
        $phone_list1   = '...';
    
        // Variables2
        $array_static2 = Array(0 => 'NA');
        $phone_list2   = "";
    
        // .. more tests
    
        // Bloco try/catch para confirmar que aqui lança excepção
        $this->scrap->getPhone($phone_list1, 'hr', '351', '9');        
    

    That should do it.

提交回复
热议问题