ecd's avatar
Level 3

How to test validation rules withoutExceptionHandling

Hello,

I'm onto a new personal project and following Uncle Bob's advices (Clean Code) I thought it'd be good to give it a shot to test every line of code. That includes testing validation rules, which I wasn't familiar with until now. But I have a bit of a phpunit workflow problem.

I'd like to add $this->withoutExceptionHandling() to my TestCase's setUp() because it is painful to go and check the laravel.log file everytime an error occurs. Problem is now that when I test a faulty validation rule, it throws an error and never goes to the assertion.

How can I get the best of both worlds : get a nice stacktrace in phpunit's console and be able to get until the end of my test?

0 likes
4 replies
frankielee's avatar

Set stopOnFailure to false

<phpunit stopOnFailure="false">
ecd's avatar
Level 3

Thanks for the suggestion, and indeed I was missing some interesting settings for phpunit but that's not exactly what I was looking for and I ended up reversing the default behaviour of phpunit with Laravel. Adding $this->withoutExceptionHandling() by default, and adding $this->withExceptionHandling() on a case-by-case basis to the tests that need it to work properly.

Please advise if anyone thinks that's a bad idea.

tykus's avatar
tykus
Best Answer
Level 104

Why would you test without exception handling by default; in the case of "feature" tests, you are no longer testing how the framework/application will handle known exceptions (such as ValidationExceptions).

Personally, the withoutExceptionHandling method is something I will use as a developer convenience while writing/refactoring a particular test example (and associated application logic). This provides an understanding of any failure; but, as soon as the test example is written and working, that line is removed from the test.

Please or to participate in this conversation.