Test-driven Development practices-Test-driven development

Source: Internet
Author: User

A Objective

I don't know if you have heard of the "Test-first development", as a development practice, in the past development, the general is to develop the user interface or class, and then write the test on this basis.

In TDD, however, the first step is to write the test case and then develop the class or user interface. To develop test cases first, the developer must be clear about the purpose of the test, the business logic of the functional modules tested, and the scenarios that need to be tested.

TDD ensures that the code for the project matches the required business, and that the functionality that was previously done can be tested in future development work.

Many students ask TDD to use that programming language, or some kind of technology, where it is clear that TDD is not a technology, but a project practice.

Lead:

What is the difference between a traditional development model and a TDD development model? What are the difficult points and advantages of TDD development? What technical knowledge points do you need to use in the specific development process of TDD? And see the author of this article through an example to illustrate the TDD development process, let you have a general understanding of TDD.

two. Traditional development mode and TDD development model

1. Traditional development Mode flow:

Project Code Development Writing test Cases –> Run test Cases , Fix code Bug

2. TDD Development Mode Process

Writing test Cases , Run the test case –> Writing Project Code , Run test Cases , Refactoring Code

three. Introduction to TDD challenges

When it comes to writing test cases, the general students feel that there is no problem, according to the existing code, along the gourd to touch the melon to the test method are the "set" again, testing what results also have to follow the code of the project.

As to whether the test code can detect the problem of the project, that is another problem, the key is to test the code to pass, then my work can be counted out.

But to write a test case before the project code, that is, I want to imagine those abstract and obscure functional points, but also to outline their outlines and details in the mind, this does not mean that I draw a cake to hunger? The problem is that I even the cake should be what it is not a spectrum, this is how desolate ah, if "blue fat" in my side is good ~

Four. Advantages of TDD

1. Ensure code quality and encourage developers to write only code that meets requirements.

"Li Lei" classmate known as sloppy king, often various items lost, such as girlfriend (object) lost, borrowed items (citation) lost, use "IO tap water" after the valve is not closed, to the warehouse (Database) to pick up goods, because forget some items, have to travel frequently and so on.

"Han Meimei" students have a deep skill, carefully crafted a Swiss army knife-like code, time-consuming 5 days (in fact, the function of customers without expansion requirements only 1 days time to complete).

In TDD practice, we need to focus on code quality and write just the right amount of code.

2. Ensure consistency of code and business requirements

Generally speaking, programmers are willing to put the function of the perfect embodiment of the code, but sometimes the days do not follow, the mind can not worry, I this code to meet business needs? In TDD, however, the first step is to write the test case and then develop the class or user interface. Because the test case should be developed first, the developer must be clear about the purpose of the test, so that TDD ensures that the project's code matches the desired business.

3. Create a concise and targeted interface

One day, "Li Lei" received the "Han Meimei" sent to a function to prepare for the breakthrough and core steps (class library and interface). Can read 3,000 times still can not understand, on the one hand is "Han Meimei" uses ancient classical Chinese and modern Latin mix to write core steps, on the other hand "Han Meimei" "Han" style 1 to 1000000 of the naming rules let "Li Lei" after reading the core steps of 30 seconds, have no idea of the first few of the first few.

In TDD practice, we should focus on creating meaningful, concise interfaces, which are especially important in working with others.

4. Communicate with users to clarify requirements

In the process of developing the code, we will always encounter a less clear point of demand, this time and demand personnel communication that is essential, understand the function of input and output to ensure the perfect task. In the process of communication also deepened the trust and tacit understanding with the customer, unconsciously can also improve the EQ, double benefit.

5. Regression testing to ensure that new changes do not affect existing functionality

After the "Han Meimei" students developed a function 3 months later, "Li Lei" received instructions from superiors, customers to expand the function, but the original function remains unchanged. After painstaking work, "Li Lei" classmate glorious completion of the task, is ready to accept everyone's praise, "Han Meimei" out to everyone complaining, that is, "Li Lei" in order to do the expansion function to do her before the function of broken, then "Li Lei" that heart ah, pull cool pull cold!

The development of TDD included regression testing, which ensured the correctness and completeness of previous functions and reduced unnecessary problems.

6. Improve the openness and extensibility of the system

All along we have to talk about sequencing, software development also has a similar process. "Li Lei" and "Han Meimei" are together "captivity" to an emergency function module, and "Li Lei" waits for "Han Meimei" to complete her function module in order to start her own module. To solve this problem, the team decided to use some technology to remove their dependencies, such as using the IOC and some design patterns so that they could develop at the same time, then assemble the two-person functional modules together.

Five. Technical knowledge points to be used in TDD development : unit Testing, Dependency injection frameworks, and mock objects

1. The workflow of TDD

The workflow of TDD is often described as " red light -on-green" refactoring: Start with a failed test, and then write the code sufficient to pass the test. Then refactor the code. Of course we do not want to see the test case can not be passed, when you continue to write the project code, so that the original can not pass the test case through the time, you will feel a hint of silk comfort, and then the code optimization refactoring, instant and some sense of accomplishment. A sip of water, the work is so happy to finish.

2. Pseudo-object, Dependency Injection box (DI/IOC) and simulation framework

In the simplest practice, the more common three-tier architecture, the UI layer to invoke the business logic layer, the business logic layer to invoke the data persistence layer.

"Han Meimei" to do business layer of code, "Li Lei" to do data layer code, so "Han Meimei" became "Huang Shiren", "Li Lei" became "Bailao", in which bitterness only "Li Lei" know! In order to change the fate, "Li Lei" decided to make a "false" data-layer object (mock object) to "Han Meimei" to use, save her every day in that his soporific.

A pseudo-object is a simple simulation of a substitute for an external resource, which typically returns a predefined response for a method when it is called, but usually does not change the response based on the input parameters.

So "Li Lei" happy to start his plan, the "Han Meimei" need to use the function of the interface to achieve (interface), and then the method of the interface in a separate simulation class only write a simple shell, the various return values are written "Han Meimei" want to sample the data, The last earnestness of the "Han Meimei" said: "Things take joy son left me ...", "Han Meimei" of course is cheerful jumped to their seats.

control reversal is when an object is created, by an external entity that regulates all objects within the system to pass a reference to it on the object to which it depends. It can also be said that the dependency is injected into the object. So, control reversal is a reversal of this responsibility about how an object obtains a reference to the object he relies on.

"Han Meimei" to get Li Lei to the pseudo-object, straight to use up, in all the classes that need pseudo-object directly using the universal "New" keyword to instantiate this pseudo-object, which takes into account the simple and affordable, the vast number of programmers enthusiasts love to do so.

But "Han Meimei" later slowly realized that is not quite right, I have many places to use the NEW Word, that is not after "Li Lei" completed his so-called real object, I also have to change my code, I put in the pseudo-object to replace the real object? I'm not the fault of myself.

"Han Meimei" hurriedly find with black box body back shoulder bag of senior, detail the current difficulties. Black box brother that is willing to be so sad, hurriedly come up with the killer "control reversal" in a trick of "dependency injection", so that the use of the class only to keep the interface of the called object, and then the dynamic injection of the instance to this interface, as long as the implementation of the interface can be arbitrarily replaced with the class, And the injected action is usually implemented by a framework such as Autofac,Unity or Ninject , and so on.

This "Han Meimei" heart steadfast, tube You "Li Lei, Zhang Lei, Wang Lei" write what pseudo object or real object, as long as your object implementation of the specified interface, I can use, and I do not have to manually create this object, worry and save time.

The simulation Framework is a series of APIs for quickly creating pseudo-objects , it can reduce duplication of code, improve coding efficiency, more commonly used for rhino, Nsubstitute, Moq and so on.

"Li Lei" and "Han Meimei" in such a harmonious cooperation, but with the increase of the task, found that the problem:

1) "Li Lei" to hand do a lot of pseudo-objects to "Han Meimei", heavy task.

2) The internal requirements for each object are different, and "Li Lei" finds it almost impossible to create these pseudo-objects in a common format.

3) Many pseudo-objects also rely on other pseudo-objects, which is simply to let the crash.

4) Many of the objects within the state need to be saved, manual to write code difficult to maintain these status indicators.

Li Lei struggled to get rid of the daily greet of "Han Meimei" by creating pseudo-objects, which fell into the vortex of creating countless pseudo-objects. So "Li Lei" crossed the ocean, Shanshan, hoping to find a beacon to solve these problems, finally Kung fu, "Li Lei" found the divine weapon to solve the problem, that is the simulation framework.

Simulation framework to help "Li Lei" quickly create a variety of "Han Meimei" needs of the simulation objects, as well as a variety of required APIs, the blink of an hand, Li Lei with this divine weapon has killed countless enemies, the corners of the mouth can not help but rise!

3. Refactoring Code

But the problem is still a win, she found that some of her functions, although the test passed, but the code is not good, often by the dark circles senior criticism, said her code quality is not high.

So she must try to optimize the code as soon as possible after the passing of the test, one is less scolded, and the other is to improve their coding level of an opportunity to check the gaps; third, the most forgetful thing, not to mention "I wait for the Ruhuasiyu girl!" "If not optimized early, I'm afraid it will be hard to get some time later."

Because the test code is already in place, so refactoring the code is also a very secure thing, if I change the wrong thing, then I write the test case certainly can not pass, this also can let me confidently to put these smelly code to unload eight pieces.

Six Operation Flow

Let's take a look at "Han Meimei" and "Li Lei" for their work steps:

1. First, Han Meimei and Li Lei analyzed their respective businesses, then Han Meimei wrote out the test cases she needed to try to get the data by using the method "Li Lei" would provide. Of course, this code is the first time the test does not pass, because the required implementation class is not yet written. Here we use a mock-up framework such as MOQ.

Test case running results, we also know, two words "sad urge"!

2. Then, "Li Lei" over there began to write the Data Persistence layer Interface (iproductrepository), "Han Meimei" to the interface provided by Li Lei, completed the Business Logic Layer (Productservice) code writing, after completion of a big breath: " The lad was finally able to force it once! ”。

A The code of "Li Lei" is as follows, in fact "Li Lei" just provided the interface (interface) to "Han Meimei", he did not start to write a specific implementation class, but Han Meimei can already work through the interface.

B The "Han Meimei" service class code is as follows, she gets to "Li Lei" to provide the data persistence layer interface and began to happily write code, everything is so flowing:

3. Next "Han Meimei" added a variety of required references, run the test case again, this smooth pass, the heart of that excitement, not to say!

4. The work is nearing the end, but glasses brother reminded that "the vast number of procedural apes should have a high degree of ideological awareness, spare no effort to improve the quality of code", in order to achieve this goal, "Han Meimei" and began to jump down the "everyone to pick up."

She found that there is a piece of code write bad, too many loops, and not neat, she wants to optimize the code, but also afraid to write good logic broken, but now there are test cases, she will not be afraid of this problem, change the wrong code, test cases will not be passed naturally.

Run the next test case, still pass, this code optimization is complete, if there are new problems can be in accordance with the gourd to continue the optimization of the painting scoop.

5. At the same time, "Li Lei" over the data Persistence layer code is almost written, you need to put the code together as "Integration test", this time the use of the IOC framework to the "Li Lei" written data layer instances injected into the business logic layer, injected instance using the AUTOFAC this IOC framework, Here we use the constructor injection, for more information on the injection framework, please g....gle the reader.

At this point, "Han Meimei" and "Li Lei" their respective work has been completed, we are not talking about each other, each optimized their respective function code, happy work continues, our TDD explained to this end!

Reference documents:

    1. Test driven Development:by Example–kent Beck
    2. Refactoring:improving the Design of Existing Code–kent Beck
    3. The Art of Unit testing:with examples in. Net–roy osherove
    4. Professional test Driven Development with C #-James Bender, Jeff mcwherter

I have recently started to learn TDD to improve my ability. In the learning process will have some experience, so will write some blog to record these ideas, interested friends can communicate with me to learn.

QQ Group: 32745894, welcome everyone to join the discussion!

Test-driven Development practices-Test-driven development

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.