Pixelairport's avatar

Best way to use database at testing

I try to start with testing and wrote my first tests. Now i want to test things with database. Normally it creates every entry in the database which is my main database. So i switch to sqlite (:memory:). That means i have to do migrations everytime. The problem is, that i use other apis to get data into the database which i need. Its an app for movies and i need to get 100 movies for each test ... What is the best way now? Normally the application caches the movies for a few hours, but testing loads it everytime again and says "too many requests".

  1. Should i only work with fake data? I mean: Should i test the api in an extra test and the rest of my application with fake data (factories)?
  2. Should i use my live database and reset everything after tests. I think this is possible but not clever.
  3. Is there a way to use cache from my original application? And is that good ... i think this can get confusing when i have to test caching stuff. And also my repositories would throw errors.

What do you think? Or what is the best way. Im new to testing and the conept is a bit confusing for me.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Should i only work with fake data? I mean: Should i test the api in an extra test and the rest of my application with fake data (factories)?

Yes. Ideally, you should not hit a third-party API in your tests. You can use a package like Laravel VCR to capture the API response once and mock all other API calls in your tests.

Should i use my live database and reset everything after tests. I think this is possible but not clever.

Ideally, no. If you need a lot of data in the database to test against, then you can use seeders to provide fixture data to test against.

Is there a way to use cache from my original application? And is that good ... i think this can get confusing when i have to test caching stuff. And also my repositories would throw errors.

Ideally, your test environment should operate completely separate from your local/production environments. You can setup the world as you need it in your tests, including if needed cache fakes to provide a canned response whenever needed

1 like

Please or to participate in this conversation.