【问题标题】:Why would a service provider not be mocked?为什么不嘲笑服务提供商?
【发布时间】:2019-09-08 05:32:32
【问题描述】:

我正在使用库向 Indeed 工作https://github.com/jobapis/jobs-indeed 发送发送请求。

我已经设置了一个提供程序,这样我就可以轻松地模拟请求,而且我不必每次使用它时都设置我的凭据。

这个库有 2 个类。查询和提供者类。 Provider 类负责发出 http 请求。

我可以模拟 Query 类,但不能模拟 Provider 类。

提供者:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use JobApis\Jobs\Client\Queries\IndeedQuery;
use JobApis\Jobs\Client\Providers\IndeedProvider;

class JobSearchServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        // Register Indeeds API
        $this->app->bind(IndeedQuery::class, function() {
            // Build the required fields for indeeds api
            $indeed = new IndeedQuery([
                'publisher' => config('services.indeed.publisher'),
                'format' => 'json',
                'v' => '2',
            ]);

            return $indeed;
        });

        $this->app->bind(IndeedProvider::class, function() {
            // Use an empty query object so that we can initialise the provider and add the query in the controller.
            $queryInstance = app('JobApis\Jobs\Client\Queries\IndeedQuery');

            return new IndeedProvider($queryInstance);
        });
    }
}

控制器:

public function searchIndeed(Request $request, IndeedQuery $query, IndeedProvider $client)
{
    dump($query);  // Returns a mockery object
    dd($client);   // Returns original object
}

测试:

public function testSearchIndeed()
{
    $user = factory(User::class)->create();

    $this->mock(IndeedQuery::class);
    $this->mock(IndeedProvider::class);

    $this->actingAs($user)
        ->get('indeed')
        ->assertStatus(200);
}

为什么模拟了 IndeedQuery 而不是模拟了 IndeedProvider?

【问题讨论】:

    标签: laravel laravel-5 phpunit


    【解决方案1】:

    找到问题了。

    如果您尝试模拟一个不存在的类,Mockery 不会引发错误。要求上课时,我的测试中有拼写错误。

    控制器

    use JobApis\Jobs\Client\Providers\IndeedProvider;
    

    测试

    use JobApis\Jobs\Client\Provider\IndeedProvider; // Notice missing 's'
    

    使用 mocky 时,如果类不存在,您将不会收到错误。因此,如果嘲笑对象没有被解析,请检查拼写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 2013-02-16
      • 2019-07-31
      • 1970-01-01
      • 2020-12-14
      • 2020-09-21
      相关资源
      最近更新 更多