Laravel: Validation Testing

API Route:

...
Route::post('/something', function (Request $request) {
  $request->validate([
    'name' => 'string'
  ]);
});
...

Test file:

public function test_validation_something() {
  $response = $this->postJson('/api/something', [
    'name' => 'hello'
  ]);
  
  $response->assertValid('name');
  
  // ---------------------------------------------
  
  $response = $this->postJson('/api/something', [
    'name' => 123
  ]);
  
  $response->assertInvalid('name');  
}

With PHPUnit Data Providers:

use PHPUnit\Framework\Attributes\DataProvider;

public static validation_something_provider() {
  return [
    'name string' => [['name' => 'hello'], true],
    'name int' => [['name' => 123], false],
    'name bool' => [['name' => true], false],
  ];
}

#DataProvider('validation_something_provider')
public function test_validation_something(array $postParams, boolean $valid) {
  $response = $this->postJson('/api/something', $postParams);
  
  if ($valid) {
  	$response->assertValid('name');
  }
  else {
  	$response->assertInvalid('name');
  }
}

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *