1

How should I organize validation in Laravel to be able to test/TDD?

I think I need to throw ValidationException from services instead of doing something in controllers, to be able to assert it in unit tests.

For example I have changePassword($user, $password, $newPassword) method in UserService where I need to check that $password is correct and that $newPassword is not empty, etc.

Should I do it like here https://stackoverflow.com/a/23595760/964478? Create a validator via Validator::make somewhere and

if ($validator->fails())
{
    throw new ValidationException($validator);
}

And in unit tests

public function should_not_change_password_if_incorrect_current_password()
{
    $user = ......;

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

    $this->userService->changePassword($user, 'incorrect', 'newPassword');
}

Or there are better ways?

Or I should not unit test it and just do acceptance testing (checking HTTP response, session, ...)?

Community
  • 1
  • 1
Alex P.
  • 3,697
  • 9
  • 45
  • 110
  • 1
    Validation at the service level? I do that in the controller where I'm handling the request. What's the advantage of doing it in the service? – John Corry Dec 03 '16 at 13:53
  • @jcorry How do you test it? Only at the acceptance test level (like perform a POST request and check errors in response/session)? I tried to do it in unit tests. Also thought that some service methods may be used in several places, so it would avoid code duplication. – Alex P. Dec 03 '16 at 14:11
  • 1
    Yes, the controller code would be best tested with acceptance/integration tests. That's where you'd test the validation. – John Corry Dec 03 '16 at 14:12

1 Answers1

-1

You may wish to mock the Validation object, and in your mock you can provide simple behavior for a failed validation and assert against that behaviour.

You could use a tool like Mockery to create simple mocks in your tests.