3

我有一个抽象类,它在其构造函数中调用公共函数。为了测试这些调用是否正确执行,我必须模拟抽象类。每当我这样做时,我都无法在构造函数中进行公共函数调用。我收到以下错误:BadMethodCallException: Method ::setData() does not exist on this mock object。以下代码可能更好地解释了我的问题。

<?php

namespace Example\Tests;

use Mockery as m;
use PHPUnit_Framework_TestCase;

abstract class Foo
{

    private $data;

    public function __construct(array $defaults)
    {
        foreach ($defaults as $key => $value) {
            $this->setData($key, $value);
        }
    }

    public function getData()
    {
        return $this->data;
    }

    public function setData($key, $value)
    {
        return $this->data[$key] = $value;
    }
}


class ExampleTest extends PHPUnit_Framework_TestCase
{

    public function testDefaultsAreAssignedToData()
    {
        $expected = ['foo' => 'bar'];

        $foo = m::mock('\Example\Tests\Foo', [$expected]);

        $this->assertEquals($expected, $foo->getData());
    }
}
4

1 回答 1

1

Usually you are using mocks as a replacement for external dependencies for your class under test. In this case you just want to test the real behaviour of the class, and you are not dealing with any dependencies for the class Foo. In this case there is really no need to mock, I would just define a concrete instance of the abstract class for testing purposes. That said, you can refactor to something like this.

class ConcreteFoo extends Foo
{
}

class ExampleTest extends PHPUnit_Framework_TestCase
{
    public function testDefaultsAreAssignedToData()
    {
        $expected = ['foo' => 'bar'];

        $foo = new ConcreteFoo($expected);

        $this->assertEquals($expected, $foo->getData());
    }
}
于 2013-09-12T19:59:56.587 回答