How to write Laravel PHPUnit tests for postman API requests - laravel

I have Postman API requests (POST request) containing grant_type = 'password', username = 'abc', password='xyz'. By passing this I get an token = 'xxx' and token_type = 'Bearer'. How do I write an phpunit test in laravel for such api requests?

you can make a test by php artisan make test:PassportTest.
Then you can use
$response = $this->json('POST','/api/token',['grant_type'=>'password','username'='abc','password'=>'xyz']);
$response-> assertJsonStructure([
'token'=>'xxx',
'token_type'=>'Bearer'
]);
You can also use $response->assertDatabaseHas($tokenTable,$data) to check if there is a record in you databse;
Cant see your database structures,so you need a little change to suit your own project.

Related

Integration API with and parametric URI, laravel or not

I want to consume a service like this
https://server.com/api/plate-number/{{plate_value}}/assistance
where plate_value is a dynamic variable.
I think i will do a form to consume this service and handle Json response.
Can i do with laravel and guzzle? Or is too much work for this?
Thx a lot
yes you can use Http to make your request:
use Illuminate\Support\Facades\Http;
$plate_value="your value";
$response = Http::get("https://server.com/api/plate-number/$plate_value/assistance");
dd($response->json());
laravel document
This is fairly simple with Laravels Http facade. Concatenate the string, by using "" string literals and set plate value in your URL and the rest is just utilizing the facade.
use Illuminate\Support\Facades\Http;
$plateValue = 42;
$response = Http::get("https://server.com/api/plate-number/$plateValue/assistance");
// Get JSON
$result = $response->json();
// Get string
$result = $response->body();
For this to work you need guzzle installed.
composer require guzzlehttp/guzzle

Acessing auth user attribute

I am in the guzzle controller making a request to an external api.
I wanna use an id from the user who is logged in.
I have been doing the request with a static id, but now i want it dynamically.
I tried like this:
$science = Auth::user()->science_id;
$client = new Client(['headers' => ['Accept' => 'application/json']]);
$request = $client->get(
'https://url_to_the_api/'.$science.'/degree',
[
'auth' => ['client', 'secret'],
]
);
$data = $request->getBody()->getContents();
return $data;
And i have the error
500(internal server error)
and this message:
"Trying to get property 'science_id' of non-object"
What am i missing?
Thanks for your time
If you are using it in web app then make sure you first check if user is already authenticated by using auth middleware or manually by using Auth::check() function.
Or
If you are trying to hit this by api that will not work here because session will not be maintained in that case. That's why JWT tokens were introduced to maintain the state of an application.
I've solved it like this:
$science = auth('api')->user()->science_id;
Thanks for the help!

Simple Laravel Passeport Route Testing

I encounter a small problem when performing unit tests for the default Passport 5.8 routes.
In fact I tested the route / oauth / clients in get mode:
/** #test */
public function getOauthClients()
{
$user = factory(User::class)->make();
$response = $this->actingAs($user)->getJson('/oauth/clients');
$response->assertSuccessful();
}
But when I want to test the route provided by default in get mode: /oauth/token , I do not know what are the steps I need to follow.
Thank you in advance.
You should try with:
Passport::actingAs(
factory(User::class)->create()
);
$response = $this->getJson('/oauth/clients');
// ...
Passport ship with some testing helpers for that purpose, like the actingAs method above.
Quoting from documentation:
Passport's actingAs method may be used to specify the currently authenticated user as well as its scopes. The first argument given to the actingAs method is the user instance and the second is an array of scopes that should be granted to the user's token:

Laravel Stripe Mocking

How can we mock Stripe in Laravel Unit Tests without using any external package like stripe-mock etc?
The job is to test the Controller feature where the secret is hardcoded and due to which test is failing.
Hey i ran into the same problem,
i am using aspectmock from codeception. Gave me some grief setting it up but im now able to mock all the responses with a json response. this way the json data goes thru the stripe classes and it throws the correct errors and returns the same objects.
hope that helps
https://github.com/Codeception/AspectMock
public function testAll()
{
$customerClass = new StripeCustomers();
test::double('Stripe\HttpClient\CurlClient', ['request' => [json_encode($this->allJsonData), 200, []]]);
$customer = $customerClass->all();
$this->assertArrayHasKey('data', $customer);
}

To create restful api for android team in Laravel 5.2

I am currently creating Rest API for Android Team using Laravel 5.2 and testing the API in RESTCLIENT.
I am just trying to get the form values which are entered in Restclient with POST method.
I have problem with POST method.. I m just not able to get the form field values. My API for GET method works fine.
Kindly guide me.
Thanks
This is how you handle POST request in laravel. Be it 5.2 or 5.4.
Route::post('books', 'BookController#store');
Controller
pubic function store(Request $request)
{
$name = $request->name;
$name = $request->get('name');
$name = request('name'); //global helper
//Your testing with api so you should return to api if you want to see it
return response()->json($name);
}
Then check in Android console if you receive $name in JSON format.

Resources