too*_*vdb 5 unit-testing facade laravel mockery
我有一个Str::random()我想测试的类。
但是当我Str::shouldReceive('random')在我的测试中使用时,我得到一个 BadMethodCallException 说该方法 shouldReceive 不存在。
我还尝试直接模拟该类并将其绑定到 IOC,但它一直在执行原始类,生成一个随机字符串而不是我在模拟上设置的返回值。
$stringHelper = Mockery::mock('Illuminate\Support\Str');
$this->app->instance('Illuminate\Support\Str', $stringHelper);
//$this->app->instance('Str', $stringHelper);
$stringHelper->shouldReceive('random')->once()->andReturn('some password');
//Str::shouldReceive('random')->once()->andReturn('some password');
Run Code Online (Sandbox Code Playgroud)
您将无法以这种方式模拟 Illuminate\Support\Str (请参阅模拟文档。这就是我测试它的方法。
在尝试生成随机字符串的类中,您可以创建一个方法来生成随机字符串,然后在测试中覆盖该方法(代码未实际测试):
// class under test
class Foo {
public function __construct($otherClass) {
$this->otherClass = $otherClass;
}
public function doSomethingWithRandomString() {
$random = $this->getRandomString();
$this->otherClass->useRandomString($random);
}
protected function getRandomString() {
return \Illuminate\Support\Str::random();
}
}
// test file
class FooTest {
protected function fakeFooWithOtherClass() {
$fakeOtherClass = Mockery::mock('OtherClass');
$fakeFoo = new FakeFoo($fakeOtherClass);
return array($fakeFoo, $fakeOtherClass);
}
function test_doSomethingWithRandomString_callsGetRandomString() {
list($foo) = $this->fakeFooWithOtherClass();
$foo->doSomethingWithRandomString();
$this->assertEquals(1, $foo->getRandomStringCallCount);
}
function test_doSomethingWithRandomString_callsUseRandomStringOnOtherClassWithResultOfGetRandomString() {
list($foo, $otherClass) = $this->fakeFooWithOtherClass();
$otherClass->shouldReceive('useRandomString')->once()->with('fake random');
$foo->doSomethingWithRandomString();
}
}
class FakeFoo extends Foo {
public $getRandomStringCallCount = 0;
protected function getRandomString() {
$this->getRandomStringCallCount ++;
return 'fake random';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1249 次 |
| 最近记录: |