Search code examples
phplaraveltestinglaravel-5faker

When using Faker in laravel, how to test the results of API calls?


I want to write tests for API calls in Laravel. I have created a model factory to seed my test database so the API calls can return something. Inside the model factory I use Faker to generate random data for the model attributes. I'm using this factory at the beginning of my test, so the data is created during runtime.

How can I test the results of the API calls? The problem is that during every execution of the test the API call can return different results, due to the randomly generated data. So I cannot just save the result of an APi call in a .json file and compare it with the actual result of the API call in the test.

I am aware of the seeJsonStructure()method ( https://laravel.com/docs/5.3/application-testing#verifying-structural-match ) but I do not want to use it.

So this is my current attempt which does not work:

$cars = factory(Car::class)->times(2)->create();

$this->json('GET', '/api/cars');

$expected = File::get('cars.json');

$this->seeJson((array) json_decode($expected));

Solution

  • You could set a seed value in Faker as described here.

    Seeding the Generator

    You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a seed() method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results.

    <?php
    $faker = Faker\Factory::create();
    $faker->seed(1234);
    
    echo $faker->name; // 'Jess Mraz I';
    

    That will give you consistent results across test runs.