为什么单元测试不应该使用数据库? [英] Why unit tests should not use database?

查看:47
本文介绍了为什么单元测试不应该使用数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读一篇文章 Evil Unit testing,我不太确定为什么要进行单元测试永远不要使用数据库、网络或文件系统.如果是网络应用呢?

Reading an article Evil Unit testing, I am not exactly sure WHY the unit tests should never use DB, network or file systems. What if it an network app?

推荐答案

单元测试用于测试代码最小单元的功能.他们不应该依赖任何可能在未来发生变化的外部资源.

Unit tests are used to test the functionality of the smallest unit of your code. They should not have any dependency on any external resource that might change in future.

举个例子,假设今天你编写了一个单元测试来测试一个执行两个数字相加的方法.

To take an example, let's say today you write a unit test that test a method that performs addition of two numbers.

public void AddNumberTest()
{
    int a = 4; // Assume 4 coming from a database.
    int b = 5; // Assume 5 coming from a database.

    int c = a + b;
    Assert.True(9, c);
}

这将在今天运行.这太酷了.

This will run today. That's totally cool.

假设您明天来更改 Add 方法的功能.现在您应该能够运行测试并且它应该通过.但是让我们假设数据库服务器(或外部资源)以某种方式关闭.然后测试失败.

Let's say tomorrow you come and change the functionality of the Add method. Now you should be able to run the test and it should be pass. But let's assume somehow the database server (or external resource ) is down. Then the test fail.

即使有人更改了数据库中的值,您也需要了解要对测试进行的更改.

Even if someone changes the values in database, you need to be aware of the change to be made to the test.

这就是你想要的???绝对不.对

这就是我们编写独立于外部资源的单元测试用例的原因.我们使用模拟和存根的地方.

That's why we write unit test cases that should be independent of external resources. That where we use mocks and stubs.

您应该能够运行一千次单元测试并且它应该始终给出相同的结果.

这篇关于为什么单元测试不应该使用数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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