【发布时间】:2019-09-23 16:11:10
【问题描述】:
我的类 Foo 有一个名为 Bar 的方法,当调用它时会记录一条调试消息。 Foo 类在其 __contruct 方法中获取 \Psr\Log\LoggerInterface $logger。我在我的 FooTest 类中创建了一个 testBar 方法,但是我的 Bar 方法中的调试方法给出了以下错误
PHP 致命错误:类 Mock_LoggerInterface_a49cf619 包含 8 个抽象 > 方法,因此必须声明为抽象或实现其余 > 方法(Psr\Log\LoggerInterface::emergency, Psr\Log>\LoggerInterface::alert, Psr\Log\ /var/www/html/myproject/vendor/phpunit/phpunit-mock-objects>/src/Generator.php(264) 中的 LoggerInterface::critical, ...) :第 1 行的 eval() 代码
我的课程代码如下
use Psr\Log\LoggerInterface;
class Foo {
private $logger;
private $myclassObject;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function Bar ()
{
// some code
$logger->debug ('debug message')
}
}
下面给出我的测试类
use PHPUnit\Framework\TestCase;
class FooTest extends TestCase
{
private $logger;
public function setUp()
{
$this->logger = $this->getMockBuilder('\Psr\Log\LoggerInterface')
->setMethods(null)
->getMock();
$this->logger->expects($this->any())
->method('debug')
->willReturn('Message Logged');
}
$this->myclassObject = $this->getMockBuilder('MyVendor\MyModule\Model\Foo')
->setMethods(['__construct'])
->setConstructorArgs(['$logger'])
->disableOriginalConstructor()
->getMock();
public function testBar()
{
$this->assertEquals($expected_result,$this->myclassObject->Bar());
}
}
我希望看到使用存根调试方法记录“消息记录”的成功单元测试
【问题讨论】: