1

I am new to unit testing and now trying to write some test cases using PHPUnit for a Laravel application. I have done one basic test which is like the following :

public function testGetPointsByApp()
{
    $this
        ->json(
            'GET',
            self::URL.'/'.$value
        )
        ->assertResponseStatus(200)
        ->seeJson([
            'status' => 'success',
        ])
        ->seeJsonStructure([
            'status',
            'message',
            'data' => []
        ]);
}

Now this is working. But I would like to know how can I test for invalid inputs and for the cases like there is not data at all with the given parameters. I am throwing corresponding exceptions in each of these cases and it will add particular messages. How can I test whether it is thrown ?

I don't want to include it to this method and would like to write some other methods to test different scenarios in the API like invalid UUID, no data etc. So for each time, I need to call the API url or this call can be done from any kind of set up function ?

Happy Coder
  • 4,255
  • 13
  • 75
  • 152

2 Answers2

1

I don't know laravel but in PHPUNIT you can test if exception is thrown with expectException function. For example for InvalidArgumentException

$this->expectException(InvalidArgumentException::class);

You can also use annotation @expectedException and there are also a lot of things that can be tested in exception like expectExceptionCode() etc.

More you can find here

Robert
  • 19,800
  • 5
  • 55
  • 85
0

Since you're not doing an Unit test (this kind of test you're doing is an acceptance test), you cannot check for the exception it self, you will look for a bad response:

$this
    ->json(
        'GET',
        self::URL.'/'.$BAD_VALUE
    )
    ->assertResponseStatus(422)
    ->seeJson([
        /* Whatever you want to receive at invalid request */
    ])
    ->seeJsonStructure([
        /* Whatever you want to receive at invalid request */
    ]);

Laravel validation errors returns 422 - unprocessable entity HTTP code.

You can check the response also for your expected error messages or something else.

Elias Soares
  • 9,884
  • 4
  • 29
  • 59
  • While throwing the exception, I am actually getting error code 417 when testing through Postman. It is actually Expectation Failed. – Happy Coder Aug 03 '16 at 05:53