且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何编写依赖于动态数据的函数的单元测试?

更新时间:2021-12-06 22:12:58

单元测试以理想的形式,应该只测试一个东西。在这种情况下,您正在测试两项内容:

Unit tests, in their ideal form, should only test one thing. In this case, you're testing two things:


  1. 您的函数的逻辑

  2. 数据库检索

因此,我建议使用以下重构器:

So I would suggest the following refactor:


  1. 将数据库检索逻辑移动到单独的函数

  2. 让您想要测试的函数调用另一个函数

  3. 函数返回数据,所以你可以单单测试你的应用程序的逻辑

  4. 如果它是有意义的(如果你只是依靠另一个库来做这个,那么希望lib已经测试),为动态检索函数编写一个单元测试,在这里你不能测试细节,但可以测试返回的数据的结构和合理性(例如,它设置了所有字段,并且是5秒内的时间现在)。

  1. Move the database retrieval logic into a separate function
  2. Have the function you want to test call that other function
  3. Mock out the function that returns data so you can unit test just the logic of your app
  4. If it makes sense (if you're just relying on another library to do this, then hopefully that lib already has tests), write a unit test for the dynamic retrieval function, where you can't test specifics, but can can test the structure and reasonableness of the data returned (e.g. it has all the fields set, and is a time within 5 seconds of now).

此外,通常在测试环境中运行单元测试是一个好主意,您可以完全控制存储的内容数据库。您不想针对生产数据运行这些操作。

Also, typically it's a good idea to run unit tests in a test environment where you have complete control over what's stored in the database. You don't want to run these against production data.