简体   繁体   English

php laravel绑定嘲讽实例失败

[英]php laravel binding mockery instance failed

I try to mock a class with Mockery. 我尝试用Mockery模拟一堂课。 I create a new Laravel projet. 我创建了一个新的Laravel项目。

I create the controller app/Http/Controllers/Mockcontroller.php with contents : 我用内容创建控制器app / Http / Controllers / Mockcontroller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class Mockcontroller extends Controller
{
    function get($id) {
        return 'FAILED';
    }
}

I want to mock the get() method, so I have modified the file tests/ExampleTest.php with this contents : 我想模拟get()方法,因此我用以下内容修改了文件tests / ExampleTest.php

    <?php

    use Illuminate\Foundation\Testing\WithoutMiddleware;
    use Illuminate\Foundation\Testing\DatabaseMigrations;
    use Illuminate\Foundation\Testing\DatabaseTransactions;

    class ExampleTest extends TestCase
    {
        /**
         * A basic functional test example.
         *
         * @return void
         */
        public function testBasicExample()
        {
            $mock = Mockery::mock(App\Http\Controllers\Mockcontroller::class);
            $mock->shouldReceive('get')
                ->with(10)
                ->andReturn('SUCCESS');
            $this->app->instance(App\Http\Controllers\Mockcontroller::class, $mock);

            $ctrl = new App\Http\Controllers\Mockcontroller();
            dd($ctrl->get(10));


        }
    }

But when I run the following command : 但是当我运行以下命令时:

vendor/bin/phpunit

I get this output 我得到这个输出

PHPUnit 5.7.5 by Sebastian Bergmann and contributors.

"FAILED"
zsh: exit 1     vendor/bin/phpunit

When I replace this line dd($ctrl->get(10)); 当我替换此行dd($ ctrl-> get(10)); by the following line : 通过以下行:

dd($mock->get(10));

I get the right text : SUCCESS. 我得到正确的文字:成功。

So, that's mock injection that failed. 因此,该模拟注入失败了。

Do you have a way to correctly inject my mock ? 您有办法正确注入我的模拟吗?

With $ctrl = new App\\Http\\Controllers\\Mockcontroller(); 使用$ctrl = new App\\Http\\Controllers\\Mockcontroller(); you create a new instance of controller without using app container, and consequently the mock. 您可以在不使用应用程序容器的情况下创建控制器的新实例,因此无需使用模拟程序。

Since you set your mock as $this->app->instance(App\\Http\\Controllers\\Mockcontroller::class, $mock); 由于您将模拟设置为$this->app->instance(App\\Http\\Controllers\\Mockcontroller::class, $mock); you need to get is as $this->app->make(App\\Http\\Controllers\\Mockcontroller::class); 您需要获取的是$this->app->make(App\\Http\\Controllers\\Mockcontroller::class); , but to be completely honest, I don't see much sense in what you are doing. ,但老实说,您的工作对我没有多大意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM