Skip to content
Advertisement

How to write a PHP unit test for a method that uses live database data?

How exactly do I write a test for a method that uses live database?

Consider this code:

JavaScript

I have A LOT of methods like the one above, and so I want to ensure that my tests are solid and will not change when the database data changes. I am looking for advice/solution towards best-in-class unit testing method and one that perhaps does not rely on changes of data in the database.

The way I could write a naive unit test now could be something like this:

JavaScript

But if the data or pricing type changes, my test will also have to change.

Advertisement

Answer

The design of your repository makes it hard to test.

Use Dependency Injection

Consider not to create the database connection within the repository class, but to inject it through the constructor instead.

JavaScript

Then it gets easy to inject a mock object.

Mock Dependency

For the testcase above, the mock could look like this:

JavaScript

This way, you’re independent from actual changes of prices and removal of products. You just have to change the test, if the structure of your data changes.

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