使用数据库创建功能单元测试的标准/最佳实践是什么?

时间:2022-10-16 00:14:06

I get the idea behind unit testing however am trying to think of a clean simple way do it when it requires database functionality. For instance I have a function that return result based off a database select query. Would the database alway have to remain the same for me to properly see that only the correct results are being returned. What is the best way to perform unit testing (in PHP) when it requires database inactivity (whether it be read, write, update, or delete)?

我得到了单元测试背后的想法,但是当它需要数据库功能时,我想要一个干净简单的方法。例如,我有一个函数,它根据数据库选择查询返回结果。数据库总是必须保持不变才能正确地看到只返回正确的结果。当需要数据库不活动(无论是读取,写入,更新还是删除)时,执行单元测试(在PHP中)的最佳方法是什么?

3 个解决方案

#1


14  

There is a whole chapter on that in the PHPUnit manual:

在PHPUnit手册中有一整章内容:

It's like with everything else when Unit-Testing. Create a known state and test your code against it to see if it returns the expected results.

单元测试就像其他一切一样。创建一个已知状态并针对它测试代码,看它是否返回预期结果。

#2


5  

It is not a unit test if it needs the database.

如果需要数据库,则不是单元测试。

#3


4  

Personally, I create a dummy testing database and populate it with a known data set for each testing run (I do that right in the setUp functions). Then the tests run against that data set, and then it's removed on tearDown...

就个人而言,我创建了一个虚拟测试数据库,并为每个测试运行填充一个已知数据集(我在setUp函数中正确执行)。然后测试针对该数据集运行,然后在tearDown上删除它...

Now, this is more of a Integration test than an Unit test (And personally I treat it differently from a unit test, run on its own schedule along with other integration tests), but it's still quite useful.

现在,这更像是一个集成测试,而不是单元测试(我个人认为它不同于单元测试,按照自己的时间表和其他集成测试一起运行),但它仍然非常有用。

#1


14  

There is a whole chapter on that in the PHPUnit manual:

在PHPUnit手册中有一整章内容:

It's like with everything else when Unit-Testing. Create a known state and test your code against it to see if it returns the expected results.

单元测试就像其他一切一样。创建一个已知状态并针对它测试代码,看它是否返回预期结果。

#2


5  

It is not a unit test if it needs the database.

如果需要数据库,则不是单元测试。

#3


4  

Personally, I create a dummy testing database and populate it with a known data set for each testing run (I do that right in the setUp functions). Then the tests run against that data set, and then it's removed on tearDown...

就个人而言,我创建了一个虚拟测试数据库,并为每个测试运行填充一个已知数据集(我在setUp函数中正确执行)。然后测试针对该数据集运行,然后在tearDown上删除它...

Now, this is more of a Integration test than an Unit test (And personally I treat it differently from a unit test, run on its own schedule along with other integration tests), but it's still quite useful.

现在,这更像是一个集成测试,而不是单元测试(我个人认为它不同于单元测试,按照自己的时间表和其他集成测试一起运行),但它仍然非常有用。