测试 - 如何对这种常见场景进行分类和处理

Testing - How this common scenario is classified and handled

我刚刚在 php 中深入研究 testing/test 驱动开发,我对如何处理遗留代码库中的一个非常典型的场景感到有点困惑。我们的代码库没有很多类,它非常面向函数式编程。

在这个伪代码示例代码中,我想为 getAndOrderUsersByAge() 编写一个测试。如您所见,它首先从我们的数据库中获取所有用户(可以说是在一个巨大的数组中,因为我们没有 objects/classes),然后对它们进行排序。这在我们的代码中当然很常见,操作或分析从数据库中获取的数据;不是对象,而是数据库行的数组。

请注意,我在 if 语句中添加了一个错误来模拟我希望我的测试捕获的错误。

//gets all users in our db into an array, then sorts them by age
function getAndOrderUsersByAge(){
     //get all users from the db
     $all_users = getAllUsers();

     //sort
     $all_users_sorted = sortUsers($all_users)

     //notice I've made a mistake here on purpose, left the "d" off of "$all_users_sorted"
     //so the function will always return false, a mistake...which I want tests to catch
     if(!empty($all_users_sorte){
         return $all_users_sorted;
     }
     else{
         return false;
     }
}

我的问题是:

1.) 测试函数 getAndOrderUsersByAge() 是单元测试、集成测试还是……?

2.) 在我的(单元?)getAndOrderUsersByAge() 测试中,我想假设 getAllUsers(从数据库获取内容的函数)行为正确,因为我只想测试 getAndOrderUsersByAge()正确的?当我阅读两本关于测试的书时,我不太确定这属于什么“概念”。这是我要“嘲笑”的地方吗?为 getAllUsers() 创建一些假数据到 return?

3.) 你会为 getAndOrderUsersByAge() 编写什么测试?我想我会写一个确保在 getAllUsers() returns 非空数组时 returned 非空数组,因为这会捕获我创建的错误。不过我不确定还有什么。

非常欢迎任何提示、推荐阅读 material 等。

1.) Is testing the function getAndOrderUsersByAge() unit testing, integration testing, or …?

您在代码级别进行的任何测试都是 unit testing,主要是测试方法、类、接口。验证一个单元或代码块的测试。

2.) In my (unit?) test(s) of getAndOrderUsersByAge(), I want to assume that getAllUsers (the function which gets things from the db)

您可以通过实际数据或模拟数据来测试getAndOrderUsersByAge()。首选模拟数据,这样您可以更好地控制测试,并且可以为 sortUsers 函数创建更多测试用例。

3.) What tests would you write for getAndOrderUsersByAge()?

测试应该是自然的,可以验证您的 sortUsers 功能。我不确定你的数据看起来如何,但一些测试可能是:

1) 将有有效数据的数据集,将通过测试

2) 名称中包含特殊字符等无效数据的数据集

3) age 字段或浮点数或超出范围的整数的数据集,基本上测试当 age 具有不同类型的数据时函数的行为

4) 具有空值的数据集

5) 1个元素数组的数据集

6) 具有重复元素数组的数据集

7) 数组中包含无效类型的数据集