I would test that my method calls internal API and returns a View.
This is my Controller:
/**
* Create a new controller instance.
*
* @param mixed|null $client a Guzzle instance. No type-hint to prevent autoload
*
* @return void
*/
public function __construct($client = null)
{
$this->middleware('auth');
$this->middleware('user.settings');
if ($client === null) {
$param = [
'base_uri' => 'http://localhost/api/v1/',
'defaults' => [
'exceptions' => false,
'verify' => false
]
];
$client = new Client($param);
}
$this->setClient($client);
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function dashboard(Request $request)
{
$user_settings = $request->get('user_settings');
$public_ip = null;
$response = $this->getClient()->get('public-ip');
$json = $response->getBody()->getContents();
$public_ip = json_decode($json,1);
return view('v110.pages.dashboard')->with('public_ip', $public_ip)->with('user_settings', $user_settings);
}
And this is the test
public function test_dashboard_call_guzzle_client_and_returns_public_ip()
{
$this->withoutExceptionHandling();
//$this->withMiddleware(); if need I can re-enable
$fixture = dirname(__DIR__,2).'/Fixtures/Api/public-ip-ok.json';
$this->assertFileExists($fixture);
$body = file_get_contents($fixture);
$this->assertTrue(is_string($body));
$mock = new MockHandler([
new Response(200,array(),$body)
]);
$handler = HandlerStack::create($mock);
$client = new Client([
'handler' => $handler,
'base_uri' => 'http://www.example.com'
]);
$data = [
'id' => 1
];
$user = factory(User::class)->make($data);
$response = $this->actingAs($user)->get(Route('dashboard'));
$response->assertViewIs('v110.pages.dashboard');
}
How can I pass that $client mocked Guzzle to the Controller?
Route is defined as
Route::get('/dashboard','HomeController@dashboard')->name('dashboard');
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire