Skip to content
Advertisement

Test failing with Integrity constraint violation error, but on the first test case it passed. Why?

I have created a test. It keep failing with this error:

JavaScript

I have googled it and read similar questions here and there but still can’t find the appropriate answer. I have defined and call the seeders on setUp, respecting the order of the table. The first call of test method are passed, the rest is failing. I see that the error has an insert call, meanwhile my test case is doing nothing but to get and count the data from it. So, what happened here?

Test

JavaScript

Migration

JavaScript

Advertisement

Answer

The test file runs without error when using in-memory sqlite database by uncommenting the below two lines in standard phpunit.xml that comes with Laravel installation

JavaScript

However while testing against MySQL it fails as you mention. Probably the seeders running before each test is a problem – as your seeders contain fetching data from json files and then converting them to associated array before running Model::create(). With in memory database such problem is not encountered but with MySQL the problem arises somehow.

There are two ways to get around this. First most simple way is to include call to run all seeders in DatabaseSeeder class and then set the value of $seed property to true on the test class where you need the seed data – more info here

JavaScript

The other option is to run the seeders with data fetched from json files only once before all tests by setting a static variable on the class and using it to control that certain seeders are run only once for all tests in the class.

JavaScript

Either of the above two will allow the tests to run with MySQL/Sqlite without any error.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement