您将无法以这种方式模拟 Illuminate\Support\Str (请参阅mockery docs。这就是我测试它的方式。
在尝试生成随机字符串的类中,您可以创建一个生成随机字符串的方法,然后在测试中覆盖该方法(代码未实际测试):
// 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';
}
}