Mockery 中的重载和别名有什么区别? [英] What is the difference between overload and alias in Mockery?

查看:16
本文介绍了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);
}

这篇关于Mockery 中的重载和别名有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆