简体   繁体   中英

PHPUnit: how to test that a method hasn't been called "yet", but will be called later in test case?

I need to test that a method is not called at some point in the test case, but is expected to be called later. Here's an example test:

<?php

class B {
    public function doSomething() {}
}

class A {
    private $b;
    private $buffer = array();

    public function __construct($b) {
        $this->b = $b;
    }

    public function x($val) {
        $this->buffer[] = $val;

        if (count($this->buffer) == 3) {
            $this->b->doSomething();
        }
    }
}

class XTest extends PHPUnit_Framework_TestCase {
    public function testB() {
        $b = $this->getMock('B');
        $a = new A($b);

        $a->x(1);
        $a->x(2);

        // doSomething is not called YET
        $b->expects($this->never())->method('doSomething');

//      $b->expects($this->at(0))->method('doSomething'); // ??????

        $a->x(3);
    }
}

In your case, I don't think it is necessary to do this. Plus, I don't see a way to check the previous calls, either. I'd rather check for the parameters flush() is executed with:

$b = $this->getMock('B');
$b->expects($this->exactly(1))
    ->method('flush')
    ->with(array(1, 2, 3));

$a = new A($b);

$a->x(1);
$a->x(2);
$a->x(3);

Usually, you'd need to check for previous methods if other mock methods are called, which you can do by telling the mocked methods exactly when they are supposed to call with at() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM