代码之家  ›  专栏  ›  技术社区  ›  mjs

如何指示一个phpunit测试预期会失败?

  •  17
  • mjs  · 技术社区  · 14 年前

    是否可以用phpunit将测试标记为“预期失败”?这在执行TDD时很有用,您希望区分真正失败的测试和由于相关代码尚未写入而碰巧失败的测试。

    5 回复  |  直到 10 年前
        1
  •  24
  •   Alexander Garden    10 年前

    我认为在这些情况下,简单地将测试标记为跳过是相当标准的。您的测试仍将运行,套件将通过,但测试运行程序将提醒您跳过的测试。

    http://phpunit.de/manual/current/en/incomplete-and-skipped-tests.html

        2
  •  11
  •   Ilia Ross    10 年前

    处理此问题的“正确”方法是使用 $this->markTestIncomplete() . 这会将测试标记为未完成。它将作为传递返回,但将显示提供的消息。见 http://www.phpunit.de/manual/3.0/en/incomplete-and-skipped-tests.html 更多信息。

        3
  •  9
  •   sixty-nine    13 年前

    我真的认为这是一个糟糕的做法,但是你可以用这种方式欺骗普菲特:

    /**
     * This test will succeed !!!
     * @expectedException PHPUnit_Framework_ExpectationFailedException
     */
    public function testSucceed()
    {
        $this->assertTrue(false);
    }
    

    更干净:

      public function testFailingTest() {  
        try {  
          $this->assertTrue(false);  
        } catch (PHPUnit_Framework_ExpectationFailedException $ex) {  
          // As expected the assertion failed, silently return  
          return;  
        }  
        // The assertion did not fail, make the test fail  
        $this->fail('This test did not fail as expected');  
      }
    
        4
  •  1
  •   Clay Hinson    14 年前

    如果您想让一个测试失败,但知道它是预期的失败,那么您可以 add a message to the assertion 将在结果中输出:

    public function testExpectedToFail()
    {    
        $this->assertTrue(FALSE, 'I knew this would happen!');
    }
    

    结果:

    There was 1 failure:
    
    1) testExpectedToFail(ClassTest)
    I knew this would happen!
    
        5
  •  1
  •   Earnie    11 年前

    上面69条的评论几乎完全符合我所寻找的。

    fail()方法在为预期的异常设置测试时很有用,如果它没有触发您希望测试失败的异常,那么它也很有用。

    $this->object->triggerException();
    $this->fail('The above statement was expected to trigger and exception.');
    

    当然,triggerException被对象中的某个内容替换。