如何编写依赖于动态数据的函数的单元测试? [英] How to write Unit Tests for functions that rely on dynamic data?

查看:188
本文介绍了如何编写依赖于动态数据的函数的单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个网站,使用函数从数据库检索数据并返回结果以显示/解析/ etc ...

Lets say you have a website, that uses a function to retrieve data from the database and returns the result to be displayed/parsed/etc...

由于从数据库检索的数据是动态的,并且可能每天的每一天都有变化,你如何正确地写这个函数的单元测试?

Since the data that is retrieved from the database is dynamic and could potentially change every second of the day, how do you properly write a Unit Test for this function?

函数应该返回一个结果数组。显然,单元测试可以测试看看是否返回数组。但是,当数组本身的内容由于不正确的MySQL查询而不正确时会发生什么?数组的大小可以为零,或者数组的内容可能不正确。由于它依赖于不断变化的数据,单元测试如何知道什么是正确的,什么不是?从单元测试本身调用数据库是必要的,所以有一些东西要比较它?

Let's say the function is supposed to return an array of results. Obviously a unit test could test to see if an array is returned or not. But what happens when the contents of the array itself are incorrect due to an incorrectly written MySQL query? The size of the array could be zero or the content of the array could be incorrect. Since it relies on ever-changing data, how would the Unit Test know what is correct and what isn't? Would calls to the database from within the Unit Test itself be necessary so there is something to compare it to?

如何正确地写一个单元测试的函数依赖动态数据?

How do you properly write a Unit Test for functions that rely on dynamic data?

推荐答案

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

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.

这篇关于如何编写依赖于动态数据的函数的单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆