Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

testing - Why unit tests should not use database?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...