【问题标题】:Mockery throws NoMatchingExpectationException when testing Laravel facadeMockery 在测试 Laravel 门面时抛出 NoMatchingExpectationException
【发布时间】:2014-09-05 10:18:01
【问题描述】:

我正在尝试测试我的一个服务类,但无法通过 PHPUnit 测试。

测试中失败的相关部分:

File::shouldReceive('put')->with('app/storage/logs/laravel.log', 'New content.')->once()->andReturn(12);

我要测试的代码(简化版):

$date = Carbon::now()->toDayDateTimeString();
$fileContent = sprintf(
    "Last maintenance check performed at %s. The old logs have been deleted.\n\n",
    $date
);

// $this->fileLocation refers to a string 'app/storage/logs/laravel.log'
return File::put($this->fileLocation, $fileContent);

我得到的异常:

Time: 1.72 seconds, Memory: 17.50Mb

There was 1 error:

1) Unit\Services\Maintenance\LogCleanerTest::testLogsAreClearedAndUpdated
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_Illuminate_Filesystem_Filesystem::put("app/storage/logs/laravel.log", "Last maintenance check performed at Tue, Jul 15, 2014 12:16 PM. The old logs have been deleted.
"). Either the method was unexpected or its arguments matched no expected argument list for this method


/home/vagrant/Code/MyApp/vendor/mockery/mockery/library/Mockery/ExpectationDirector.php:93
/home/vagrant/Code/MyApp/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:211
/home/vagrant/Code/MyApp/app/Code/Services/Maintenance/LogCleaner.php:19
/home/vagrant/Code/MyApp/app/Code/Services/Maintenance/LogCleaner.php:19
/home/vagrant/Code/MyApp/app/tests/Unit/Services/Maintenance/LogCleanerTest.php:30
/home/vagrant/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:179
/home/vagrant/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:132

谁能解释我做错了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: php laravel laravel-4 phpunit mockery


    【解决方案1】:

    类似:

    File::shouldReceive('put')->with('app/storage/logs/laravel.log', 'Last maintenance check performed at')->once()->andReturn(12);
    

    应该可以。你说嘲讽期待“新内容”。作为第二个参数,但您的代码正在发送“上次维护检查...”。我相信如果不能匹配确切的字符串,默认情况下嘲弄会尝试正则表达式匹配。

    【讨论】:

    • 谢谢。我现在可以通过测试,但是只有当两个字符串完全匹配时才会发生。任何其他想法如何让 Mockery 识别部分文本匹配(或者甚至可能)?
    • @kajetons 重点是测试应该为您提供与您期望的完全匹配,否则这可能表明存在错误。
    • 还有其他写期望的方法,这样你就不需要完全匹配了。请参阅优秀的mockery documentation。但是,正如@TheShiftExchange 所指出的,关键是您的输出符合您的预期,因此请谨慎使用这些方法。
    猜你喜欢
    • 2016-12-26
    • 2013-08-26
    • 2014-03-25
    • 2018-02-16
    • 2013-09-08
    • 2019-04-15
    • 2017-04-30
    • 2014-07-08
    • 1970-01-01
    相关资源
    最近更新 更多