I'm working with an API class that connects to IGDB, which is a video game database. There's a method named search(query) that returns a JSON object with video game titles related to the provided query. The issue I'm facing is that since the database can change (new games can be added), running search(some_game_title) might yield different results each time, which leads to inconsistent tests. I'm unsure how to unit test this method effectively. Should I consider this a unit test or more of an integration test due to the external database dependency?
6 Answers
If getting duplicate titles is a problem, consider deduplicating your query results. Remember, you can't control the quality of the source database—just focus on querying it effectively to get the best results. In cases where multiple titles exist, you might need to check additional fields like release dates to distinguish them. Sometimes, you do find legit repeats like remasters!
Since your test relies on an external data source, it's not technically a unit test. I wouldn't classify it as an integration test either since you're dealing with something you can't fully control. To effectively isolate your code, focus on testing two aspects: ensure your code makes a properly formatted HTTP request to IGDB, and verify it correctly interprets the response. You can accomplish this by mocking the HTTP request, but the method you choose will depend on your programming language and the HTTP client you're using.
A good approach is to create an interface and a class for database operations. By having a database interface, you can easily mock its functionality in your tests, allowing for consistent results.
To unit test effectively, you must mock out all side effects. Determining what qualifies as a side effect can be tricky, but any component expected to change with each call should definitely be mocked. The goal is to write testable code that minimizes these side effects from the get-go!
Just mock the database! Most programming languages have libraries for this. You could also use an in-memory database or an SQLite instance during your tests if it matches your database dialect.
If you can't mock the database dependency, then you really can't consider that method a true unit test. It's essential to isolate the function from any external elements for it to qualify as a unit test.
Exactly! This confusion between unit and integration tests is pretty common. Learning to mock external data sources is key for real unit testing.