Programmer's architectural design path (4): Unit testing

Source: Internet
Author: User
In the process of leading the team, the performance problem is still well solved, and the most negative idea is: "Well, it's just a little more. do you want me to leave it simple ?", But you need to write the test code! Based on my experience

In the process of leading the team, the performance problem is still well solved, and the most negative idea is: "Well, it's just a little more. do you want me to leave it simple ?", But you need to write the test code! Based on my experience, "test-driven" is one of the most controversial topics. The Advertiser and the opponent are both distinct and have a lot of arguments and proofs. I remember a previous article titled "The company didn't ask you to write the test code", and the following is a crazy one.

At the beginning of my project, I gave up the test drive, but the biggest reason was "lazy ". But in the end, I made up my mind to start the "test-driven" practice. I did not call out a Bug for two days and nights at a time. after being exhausted, I reluctantly accepted this reality: testing is still very useful-even the code written by yourself. My previous series of blogs have repeatedly stressed that architecture is helpless. The reality is that problems drive you to do things you didn't actually want to do. You can't understand the behavior that looks like "getting off your pants and farting", usually because you have never encountered any real problems. (Look, can the university teach you these things ?)

Even if you do not have much development experience, you should be able to imagine that the biggest problem with unit testing is that it takes time to write, so is it worthwhile to spend this? This is determined by your architecture goals or your needs. If the system is a molding and delivered for use, it will almost never be changed since then, then one-time manual testing is enough. However, if your system is constantly revised, this test is necessary. The simplest consideration is that I have to perform a manual test for every change. it will not take me more time to get something "automated. Unit testing can be understood as an automated testing tool.

However, the reason for "automation" is far from enough. Because you immediately think of changing the code for each requirement, you have to change the test code accordingly? Without the test code, I only need to change the development code. now with the unit test, I have to change the test code. Originally, I only maintained one set of code. now I have added a set of code out of thin air and need to maintain it. This does not increase the maintenance cost, but does it contradict your "maintainability" architecture goal? Is it a set of code that is well maintained, or is it better to maintain the two sets of code?

This is a very good question. it is suitable for many scenarios (for example, in a layered architecture, you say that stratified decoupling is not actually changed from the UI layer to the database, and each layer has to be changed ?). I can give the following answers:

1. do I have to perform a test after the development code is modified, regardless of whether there is a unit test? No unit test does not mean that your code does not need to be tested, but you have manually tested it again. Remember: Your work is not just about writing code!

2. conduct manual tests and change unit tests. the consumption ratio of the two depends on the number of test reuse times. A manual test may take 5 minutes to complete, and it may take 20 minutes to change the unit test code. However, if the test runs 100 times, the unit test will win the manual test.

3. where are you talking about? What functions will be changed 100 times? I didn't say that your function would change to 100 times. I said that the test would run 100 times. Is there a difference? You may still be confused, right? Okay, let's tell a story.

A young man is reluctant to write test code. The boss has nothing to do with him, and does not have that much energy to grind his teeth, so the boss writes a unit test on his own. This guy needs to review the code before submitting it. the boss can always find out its code problems again and again. He logged on to the system. The boss told him that the point system had been changed. he changed the points and the boss told him that the system had been changed; he changed the message system again, and the boss told him that there was still a problem with the login ...... So he crashed. "What is this TM system "? In the end, he finally turned back. Why does the boss always know that the changes will affect it? Is the boss thinking so rigorous? The boss smiled while hiding, so he didn't tell you, "I just ran a unit test once ".

This boss is me. I deliberately told him all the problems at one time, and I had to torture him again and again so that his pain could be engraved into the bones. Finally, I want to ask him:

• Are you so confident in your code?

• Can you discover these problems without my review (I also rely on unit testing?

• If our project has been deployed to the production environment, and the damage caused by your changes has not been discovered, then what will happen?

This time, he is convinced. Later, he used NUnit in a twist. If he fails to pass test case in every change, he will be excited to me and complain by the way. I don't want to smile, the kind of sureness of the green light on the screen, and the surprise after the red light burst unexpectedly, people who have never experienced it can't feel it.

In fact, when the relationship between objects becomes more and more complex, like a dense network, a local change is likely to trigger an extremely complex chain reaction. Therefore, for the sake of insurance, all possible components should be tested (so-called "regression testing "). At this time, if only manual testing is performed, there will be two problems:

• It's hard to determine the test boundary (those parts may be affected), so let's think about it out of thin air, bro!

• High Test cost. In addition, the cost is quite boring and tedious-no one is willing to do this. It is said that the salaries of testers in many companies are higher than those of developers. Why? It's simple, boring, and nobody wants to do it!

Okay. I suppose you have realized the importance of unit testing and are eager to try it out. Next, I have to put a lot of cold water on you: unit testing is not so easy to write! To some extent, writing unit tests is more difficult than writing development code. It is rare that none of the companies I work for have had successful cases.

About a few years ago, I fixed a bug in my company. The boss told me, "you have a core function. run a unit test ".

"Wow! We have a unit test ?" A feeling of height quickly filled the whole body and finally saw the legendary Unit!

After a while, you can run. try it-my mom? Why are there so many red lights? I am really scared. is this all caused by my changes?

The boss is the boss. Don't worry. "How many can I count ?"

"Ah ?" I thought I was wrong. how many connections do I have? You have to get all of them through ?!

After a while, I finally figured it out. I ran the code before and after the change, and checked whether the failure was the same. if it was the same, it would be OK. For example, in the past, there were eight connections, but now there were eight connections, so we can!

I have never understood why I didn't pass the eight failed unit tests? What is this? Until I start writing unit tests on my own. Ah! There are traps everywhere, jumping out of the traps and entering the big pits. There are also traps under the big pits. The front is the back of the traps, and there are a pile of serial traps ......

Unit tests are easy to run! The reason is that your development code logic is not wrong, but that the test environment/data is faulty. To test, we must have data. The construction of this data is not as simple as we think. Taking the point system in our home startup project as an example, assuming a simple requirement: The author of the blog should earn some points when the blog is liked, the number of points is calculated by the conversion of all the available coins of the likes (simplified ). The data to be prepared includes: blog, author, and author with points; likes and one person with a certain number of available coins. This is acceptable, but there are a bunch of problems as follows:

• Where do the points of the author come from? For the sake of encapsulation, the user's points are read-only. how do you set this value in unit testing?

• Either write code and simulate the author's acquisition of points through other behaviors (publish an article to answer questions, etc.), which will open up a new round of nightmare;

• If you use Mock or reflection to forcibly set it, the author's point Acquisition history is omitted. Therefore, if the user's "Point History" is null and then "add points" to the user, an exception is reported.

• Even worse, when you think you have finished everything, you suddenly find that this blog must be "published" first, and once published, the author earned a certain number of points, so the points you set have changed!

•......

• Similar problems may occur when you like the currency of a person. How can I set the available currency? will it be accidentally changed during the test?

• Likes are encapsulated into a method. running this method will check whether the likes have liked this article before. Therefore, there should be a "likes history ", A new one is required even if it is empty. Otherwise, the null exception occurs.

•......

At that time, I threw my mouse! It's so bad! In addition, I still completely isolated the database. I really don't know how to perform unit tests by retrieving data from the database? At this time, I suddenly realized that in actual work, I had to work overtime to catch up with the progress. one by one, I had no time for restructuring. how could I squeeze the time to write unit tests? Even if you start to write more ambitious, as the system becomes increasingly complex, the cost of maintaining unit testing is also increasing, or even more complex, so giving up has become the only choice for most projects.

When I work in a company, most people work like this. if I can push it, I will push it. After the code is developed and written, we can basically run it. we should hand it over to the tester! Well, isn't it? In addition, the test time is not counted in the development time of my project. I finally completed the development task on time. Tired. take a break and let the test be busy. haha ......

But I am a light pole commander. I have no testers! In one or two cases, I was really preparing to recruit one or two testers. But fortunately, my inherent frugal virtues (that is, "being") let me calm down. I just thought: the test can only tell you a bug, not the root cause. I have no unit test. I have to debug it in one step for two days? This is caused by the complexity of the system itself, or the unreasonable code organization, and cannot be attributed to unit tests. Isn't there still so many open source codes with detailed unit tests? How did they do it? If you pay for unit testing, you will surely get a reward! Think about companies that do not have a unit test, a super large testing team, or a smoke system, are you willing to take this path?

So I keep telling myself, don't worry, calm and meticulous. Finally, I took a step-by-step by step to sort out this mess and finally found a way for me to gradually complete unit tests, some potential problems in the development code have also surfaced, and I have eliminated them one by one. Run the unit test again. all the way to the green light, haha! What's even more miraculous is that the bug that has plagued me for two days does not know when it will disappear?

Later, I saw a saying that the tested code is not necessarily good code, but the bad code is almost impossible to be tested. I think so! Deeply coupled code, writing their unit tests, is difficult to go to Qingtian; but in turn, we can continue to improve and refactor the development code based on tests, as long as we stick to it, the quality of the final code is almost the same.

Therefore, for me, it is enough to argue whether unit tests are valuable! Think about how to stick to unit testing.

Finally, if you are interested, you will notice that I have been using "unit testing" instead of "test-driven ". Because the test drive is a broader concept and a new world! Unit testing is only a small part. in the next blog, I will explain how I tried to apply the test-driven concept to project development management. Here, we need to emphasize the following: write test first.

Write the development code at the beginning, and write the unit test after writing. This is a habit of many developers. I often make such mistakes and forget it when I leave nothing to worry about. The biggest problem in doing so is that "test-driven" is not actually implemented ". You are actually driven by development. Naturally, what is the significance of writing the test according to the developed if... else? By doing so, we will constantly strengthen the impression that testing is useless, because testing simply overwrites the development code. My prescription is:

• Unit test code and development code are compiled by different personnel

• If you cannot do the above, write the unit test first.

• If you cannot connect to the above, write the unit test again until a bug occurs.

Article 3 some may be unable to understand this, not to say that unit testing is heavy or? Why do I have to wait until a bug occurs? The answer is: lazy! Remember, we programmers are the lazy people in the world and never do anything meaningless! It is meaningless to write the development code first and then test again. if it is meaningless, you should simply not do it. But you can enable "optimistic" (or "Lazy "?), I am optimistic that my code is okay, maybe it's okay, right? If a problem occurs, make a remedy. in this case, we should use unit tests to display the problem, because according to Murphy's law, it has a problem, in the future, problems may continue. At this time, do not be lazy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.