PHPUnit - Mocked方法一旦失败就会被调用

时间:2015-12-11 19:51:03

标签: php phpunit

我不知道它是否是正常的PHPUnit行为,但是我遇到了使用模拟生成器开发测试的障碍。我需要检查一次是否调用了一个方法,所以我开发了一个简短的例子:

ClassA.php

<?php

class ClassA
{
    public function foo()
    {
        // Do stuff
    }
}

ClassB.php

<?php

require_once "ClassA.php";

class ClassB
{
    /**
    * @var ClassA
    */
    private $objA;

    /**
    * @param ClassA $objA
    */
    public function __construct(ClassA $objA)
    {
        $this->objA = $objA;
    }

    public function bar()
    {
        //$this->objA->foo();
    }
}

ClassAMocks.php

<?php

require_once "ClassA.php";

class ClassAMocks extends \PHPUnit_Framework_TestCase
{
    public function getClassAMock()
    {
        $mock = $this->getMockBuilder('ClassA')->getMock();
        $mock->expects($this->exactly(1))->method('foo');
        return $mock;
    }
}

ClassBTest.php

<?php
require_once "ClassA.php";
require_once "ClassB.php";
require_once "ClassAMocks.php";

class ClassBTest extends \PHPUnit_Framework_TestCase
{
    public function testBar()
    {
        $objAMock = new ClassAMocks();
        $objB = new ClassB($objAMock->getClassAMock());
        $objB->bar();
    }
}

使用此设置,因为未调用ClassA的方法foo(已注释),测试应该失败,但结果如下:

$ phpunit ClassBTest.php
PHPUnit 4.1.4 by Sebastian Bergmann.

.

Time: 31 ms, Memory: 3.00Mb

OK (1 test, 0 assertions)

测试通过u__u。然后,如果我在测试类中创建模拟类:

ClassBTest.php

<?php
require_once "ClassA.php";
require_once "ClassB.php";

class ClassBTest extends \PHPUnit_Framework_TestCase
{ 
    public function testBar()
    {
        $mock = $this->getMockBuilder('ClassA')->getMock();
        $mock->expects($this->exactly(1))->method('foo');

        $objB = new ClassB($mock);

        $objB->bar();
    }
}

并重新执行phpunit:

$ phpunit ClassBTest.php
PHPUnit 4.1.4 by Sebastian Bergmann.

F

Time: 29 ms, Memory: 3.00Mb

There was 1 failure:

1) ClassBTest::testBar
Expectation failed for method name is equal to <string:foo> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

现在它按预期失败了。那么我们不能在测试类之外创建模拟?我把所有的模拟都拆分成了分开的类,以便重复使用它们,所以,如果有人遇到同样的问题,我将非常感谢你的帮助:)

谢谢你,周末愉快!

0 个答案:

没有答案