为使用数据库的功能创建单元测试的标准/最佳做法是什么?[英] What are standard/best practices for creating unit tests for functionality using databases?

本文是小编为大家收集整理的关于为使用数据库的功能创建单元测试的标准/最佳做法是什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我得到了单元测试背后的想法,但是当它需要数据库功能时,试图考虑一种干净的简单方法.例如,我有一个函数,该函数基于数据库选择查询.数据库至上是否必须保持相同的状态才能正确地看到只有正确的结果正在返回.当需要数据库无效(无论是读,写,更新还是删除)时,执行单元测试(在PHP中)的最佳方法是什么?

推荐答案

Phpunit手册中有一整章:

单位测试时的其他所有内容.创建已知状态并针对它测试您的代码,以查看它是否返回预期结果.

其他推荐答案

就个人而言,我创建了一个虚拟测试数据库,并为每个测试运行的已知数据集填充它(我在setUp函数中正确地做到这一点).然后测试与该数据集进行,然后在tearDown ...

上将其删除.

现在,这更像是一个集成测试,而不是单位测试(我个人与单位测试的对待不同,按照自己的时间表以及其他集成测试进行运行),但仍然非常有用.

其他推荐答案

如果需要数据库,则不是单位测试.

本文地址:https://www.itbaoku.cn/post/597647.html

问题描述

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)?

推荐答案

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

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.

其他推荐答案

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...

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.

其他推荐答案

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