Mockery 中的重载和别名有什么区别?
我不熟悉使用 Mockery 并与术语 alias
和 混淆>重载
.谁能给我解释一下什么时候用哪个?
I am new to using Mockery and confused with the terminology alias
and overload
. Can anyone please explain to me when to use which?
推荐答案
Overload
用于创建实例模拟".当创建一个类的新实例时,这将拦截"并且将使用模拟.例如,如果要测试此代码:
Overload
is used to create an "instance mock". This will "intercept" when a new instance of a class is created and the mock will be used instead. For example if this code is to be tested:
class ClassToTest {
public function methodToTest()
{
$myClass = new MyClass();
$result = $myClass->someMethod();
return $result;
}
}
您将使用 overload
创建一个实例模拟,并像这样定义期望:
You would create an instance mock using overload
and define the expectations like this:
public function testMethodToTest()
{
$mock = Mockery::mock('overload:MyClass');
$mock->shouldreceive('someMethod')->andReturn('someResult');
$classToTest = new ClassToTest();
$result = $classToTest->methodToTest();
$this->assertEquals('someResult', $result);
}
Alias
用于模拟公共静态方法.例如,如果要测试此代码:
Alias
is used to mock public static methods. For example if this code is to be tested:
class ClassToTest {
public function methodToTest()
{
return MyClass::someStaticMethod();
}
}
您将使用 alias
创建一个别名模拟,并像这样定义期望:
You would create an alias mock using alias
and define the expectations like this:
public function testNewMethodToTest()
{
$mock = Mockery::mock('alias:MyClass');
$mock->shouldreceive('someStaticMethod')->andReturn('someResult');
$classToTest = new ClassToTest();
$result = $classToTest->methodToTest();
$this->assertEquals('someResult', $result);
}
相关文章