我有一个使用以下两个文件的简单Lumen应用程序,即在请求根路由/时,它请求使用GuzzleHttp\Client获取URL
routes/web.php
<?php
$router->get('/', ['uses' => 'MyController@index', 'as' => 'index']);app/Http/Controllers/MyController
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
class MyController extends Controller {
protected $client;
public function __construct() {
$this->client = new Client();
}
public function index( Request $request ) {
$response = $this->client->request( 'get', 'https://www.google.com/' );
return Response()->json( [ 'status' => $response->getStatusCode() ] );
}
}但是,我想编写一个$response->getStatusCode()将返回444的测试,因此我编写了下面的测试,尝试在GuzzleHttp\Client中模拟getStatusCode()方法
<?php
use GuzzleHttp\Client;
class MyTest extends TestCase {
protected $instance;
public function testMyRoute() {
$client = Mockery::mock( Client::class )
->shouldReceive( 'getStatusCode' )
->once()
->andReturn( 444 );
$this->app->instance( Client::class, $client );
$this->json( 'get', '/' )->seeJson( [ 'status' => 444 ] );
}
public function tearDown() {
parent::tearDown();
Mockery::close();
}
}但是运行phpunit失败:
~/experiment/lumen-test/testing » phpunit
PHPUnit 5.7.27 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 868 ms, Memory: 14.00MB
There was 1 failure:
1) MyTest::testMyRoute
Unable to find JSON fragment ["status":444] within [{"status":200}].
Failed asserting that false is true.
~/experiment/lumen-test/testing/vendor/laravel/lumen-framework/src/Testing/Concerns/MakesHttpRequests.php:288
~/experiment/lumen-test/testing/vendor/laravel/lumen-framework/src/Testing/Concerns/MakesHttpRequests.php:213
~/experiment/lumen-test/testing/tests/MyTest.php:15
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.这表明嘲笑没有产生任何效果。我在这里错过了什么?
编辑-1
在按照@sam的Mocking GuzzleHttp\Client for testing Lumen route注释修改了Mocking GuzzleHttp\Client for testing Lumen route构造函数之后,我对测试进行了如下修改:
use GuzzleHttp\Psr7\Response;-
public function testMyRoute() {
$response = new Response(444);
$client = Mockery::mock( Client::class )
->makePartial()
->shouldReceive( 'request' )
->once()
->andReturn( $response );
$this->app->instance( Client::class, $client );
$this->json( 'get', '/' )->seeJson( [ 'status' => 444 ] );
}发布于 2018-04-10 15:35:48
在构造函数中实例化Client,这意味着它不会被解析出容器。您的控制器应该在构造函数中接受Client作为参数,该参数将由Laravel解析出容器。
public function __construct(Client $client = null) {
$this->client = $client ?: new Client;
}这将创建一个新的Client,如果没有提供的话。
https://laravel.com/docs/5.6/container#resolving
自动注入 或者,更重要的是,您可以“键入”由容器解析的类的构造函数中的依赖项,包括控制器、事件侦听器、队列作业、中间件等等。实际上,这就是大多数对象应该由容器解析的方式。
https://stackoverflow.com/questions/49757488
复制相似问题