What is the difference between overload and alias in Mockery?

前端 未结 2 963
盖世英雄少女心
盖世英雄少女心 2021-01-02 12:08

I am new to using Mockery and confused with the terminology alias and overload. Can anyone please explain to me when to use which?

2条回答
  •  北海茫月
    2021-01-02 12:28

    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;
        }
    }
    

    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 is used to mock public static methods. For example if this code is to be tested:

    class ClassToTest {
    
        public function methodToTest()
        {
            return MyClass::someStaticMethod();
        }
    }
    

    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);
    }
    

提交回复
热议问题