Why unit tests should not use database?

我只是一个虾纸丫 提交于 2020-07-03 01:36:32

问题


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?


回答1:


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.

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.

Is that what you want??? Absolutely not. Right

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

You should be able to run unit test a thousand times and it should give the same results always.




回答2:


Unit testing is not intended to test the complete functionality of an application. It is meant to make sure that definable modules of code work as expected. To test an application it is not enough to use unit tests. You must also perform functional testing and regression testing. Database access falls outside the scope of unit testing, so you would not write unit tests that include database access. You would include database access testing in your functional tests. Similarly, if you have a network app, you would not include network access in your unit tests. In both cases you would unit test the code that manipulates the data that it gets from the db or the network using simulated-known data and leave the actual access out of it.

To reiterate, it is not enough to just unit test an app.



来源:https://stackoverflow.com/questions/15450957/why-unit-tests-should-not-use-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!