gpt4 book ai didi

PHPUnit 和 Mock 对象不起作用

转载 作者:行者123 更新时间:2023-12-04 05:34:35 25 4
gpt4 key购买 nike

我不确定是我做错了什么,还是 PHPUnit 和模拟对象的错误。基本上我想测试是否 $Model->doSomething()$Model->start() 时调用被触发。

我在 VirtualBox 中使用 Ubuntu,并通过 pear 安装了 phpunit 1.1.1。

完整代码如下。任何帮助将不胜感激,这让我发疯。

<?php
require_once 'PHPUnit/Autoload.php';

class Model
{
function doSomething( ) {
echo 'Hello World';
}

function doNothing( ) { }

function start( ) {
$this->doNothing();
$this->doSomething();
}
}

class ModelTest extends PHPUnit_Framework_TestCase
{
function testDoSomething( )
{
$Model = $this->getMock('Model');
$Model->expects($this->once())->method('start'); # This works
$Model->expects($this->once())->method('doSomething'); # This does not work
$Model->start();
}
}
?>

PHPUnit的输出:
There was 1 failure:

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


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

最佳答案

正如您所发现的,您需要告诉 PHPUnit 要模拟哪些方法。此外,我会避免为您直接从测试中调用的方法创建期望。我会这样写上面的测试:

function testDoSomething( )
{
$Model = $this->getMock('Model', array('doSomething');
$Model->expects($this->once())->method('doSomething');
$Model->start();
}

关于PHPUnit 和 Mock 对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com