单元测试在第n次调用函数时抛出异常

Sha*_*ane 9 php phpunit

假设你有一种最终归结为的方法

class Pager
{
    private $i;

    public function next()
    {
        if ($this->i >= 3) {
            throw new OutOfBoundsException();
        }

        $this->i++;
    }
}
Run Code Online (Sandbox Code Playgroud)

你将如何对这门课进行单元测试.即测试是否在next()使用PHPUnit 的第三次调用时抛出异常?我添加了我的尝试作为答案,但我不确定这是否真的是要走的路.

Pee*_*Haa 8

如何测试null前两个调用,并测试抛出的异常,如下所示:

class PagerTest
{
    public function setUp()
    {
        $this->pager = new Pager();
    }

    public function testTooManyNextCalls()
    {
        $this->assertNull($this->pager->next());
        $this->assertNull($this->pager->next());
        $this->assertNull($this->pager->next());

        $this->setExpectedException('OutOfBoundsException');
        $this->pager->next();
    }
}
Run Code Online (Sandbox Code Playgroud)