. NET unit test Art-1. Getting Started

Source: Internet
Author: User

Opening : The recent book "The Art of unit testing " by Roy Osherove is quite rewarding. Therefore, it is recorded and divided into four parts to share the written, with you share. As a primer, this article introduces the basics of unit testing, such as how to use a test framework, basic automated test properties, and three different types of tests. I believe you can write unit tests from ignorance to passing levels, which is also the goal of the original book author.

Series Catalog:

1. Getting Started

2. Core Technologies

3. Test code

4. Design and process

I. Unit Test Basics 1.1 What is unit testing

A unit test is a piece of automated code that calls the unit of work that is being tested and then examines some assumptions about the individual final result of the unit.

Unit testing is almost always written in the unit test framework. Unit tests are easy to write and can be run quickly. Unit tests are reliable, readable, and maintainable.

As long as the product code does not change, the result of unit testing is stable.

1.2 Differences from integration testing

Integration testing is a test of a unit of work that does not have complete control over the unit being tested and uses one or more of its real dependencies, such as time, network, database, thread, or random number generator.

In general, integration testing uses real dependencies, while unit tests isolate the test unit from its dependencies to ensure that the unit test results are highly stable and that it is easy to control and simulate any aspect of the behavior of the unit being tested.

II. test-driven Development Fundamentals 2.1 traditional Unit test flow

2.2 Overview process for test-driven development

As shown, TDD differs from traditional development in that we first write a test that will fail, then create the product code and make sure that the test passes, and then refactor the code or create another test that will fail.

Three, the first unit Test 3.1 NUnit Unit Test framework

NUnit was ported directly from the popular Java Unit Test framework JUnit, and the NUnit was greatly improved in terms of design and usability, and there was a big difference with junit, which injected new vitality into the evolving testing framework ecosystem.

As a. NET programmer, how can I install NUnit in VS and run tests directly in VS?

Step1. Find NUnit in NuGet and install

Step2. Find NUnit Test adapter in NuGet and install

3.2 LogAn Project Introduction

  LogAn (Log and Notificaition)

Scenario: The company has many in-house products for monitoring the company's applications at the customer site. All of these monitoring products write log files, and log files are stored in a specific directory. The format of the log file is made by your company and cannot be resolved with existing third-party software. Your task is to implement a product, analyze these log files, search for specific situations and events, and this product is Logan. This product should notify the relevant person when a specific situation or event is found.

In this unit test practice, we will write the tests step by step to verify the parsing, event recognition, and notification capabilities of Logan. First, we need to understand the use of NUnit to write unit tests.

3.3 Writing the first Test

(1) Our test begins with the following Loganalyzer class, which is temporarily only one method Isvalidlogfilename:

     Public class Loganalyzer    {        publicbool isvalidlogfilename (string  fileName)        {              If (Filename.endswith (". SLF"))            {                returnfalse;            }             return true ;        }    }

This method checks the file name extension to determine if a file is a valid log file.

Here in the IF deliberately removed a! operator, so this method contains a bug-when the file name ends with. SLF, it returns false instead of returning true. In this way, we can see what is displayed during the test run when the test fails.

(2) Create a new class library project named Manulife.LogAn.UnitTests (the project under test is named Manulife.LogAn.Lib). Add a class that is named LogAnalyzerTests.cs.

(3) A new test method is added to the Loganalyzertests class named Isvalidfilename_badextension_returnsfalse ().

First, we want to make clear how to write test code, in general, a unit test usually contains three behaviors:

Therefore, based on the above three behaviors, we can write the following test methods: (where assertions are partially using the Assert class provided by the NUnit framework)

  [Testfixture]  public  class   loganalyzertests {[Test]  public  void   isvalidfilename_ Badextension_returnsfalse () {loganalyzer Analyzer  = new  
   
     Loganalyzer ();  
    bool  result = Analyzer. Isvalidlogfilename (
                 Filewithbadextension.foo   );        Assert.AreEqual ( false  , result); }    }
   

where properties [Testfixture] and [test] are unique properties of NUnit, NUnit uses the property mechanism to identify and load tests. These properties are like bookmarks in a book that help the test framework identify important parts of the documented assembly and which parts are tests that need to be called.

1.[testfixture] Load a class that identifies the class as a class that contains automated NUnit tests;

2.[test] On a method, identifying the method is an automated test that needs to be called;

In addition, the specification of the name of the test method, usually contains three parts: [Unitofworkname]_[scenarioundertest]_[expectedbehavior]

1.UnitOfWorkName methods, a set of methods, or a set of classes that are tested

2.Scenario test assumptions such as "Login Failed", "Invalid user" or "password correct", etc.

3.ExpectedBehavior you anticipate the behavior of the tested method under the conditions specified in the test scenario

3.4 Running the first Test

(1) After writing the test code, click "Test", "Run", "all tests"

(2) Then, click "Test", "window", "Test window Manager", you will see the following scenarios

As can be seen, we have to test the method does not pass, we expect (expected) The result is false, and the actual (Actual) result is true.

3.5 Continue adding test methods

(1) We usually take the code coverage into account during unit testing, click "Test", "Analysis Code Coverage", "all tests", you can see the following results:80%

(2) At this point, we need to come up with a perfect test strategy to cover all the situations, so we add some test methods to improve our code coverage. Here we add two methods, one to test the uppercase file extension, and one to test the lowercase file name extension:

[Test] Public voidisvalidfilename_goodextensionlowercase_returnstrue () {Loganalyzer Analyzer=NewLoganalyzer (); BOOLresult = Analyzer. Isvalidlogfilename ("FILEWITHGOODEXTENSION.SLF"); Assert.AreEqual (true, result); } [Test] Public voidisvalidfilename_goodextensionuppercase_returnstrue () {Loganalyzer Analyzer=NewLoganalyzer (); BOOLresult = Analyzer. Isvalidlogfilename ("filewithgoodextension. SLF"); Assert.AreEqual (true, result); }

The test results are as follows:

Then take a look at code coverage:100%

(3) In order for all tests to pass, we need to modify the source code, instead of using case-insensitive string matching:

     Public BOOL Isvalidlogfilename (string  fileName)    {        if (!filename.endswith (". SLF", Stringcomparison.currentcultureignorecase))        {            return false ;        }         return true ;    }

At this point, let's run all the tests (and choose to run the failed tests) to see the red-to-green thrill. The concept of unit testing is simple: only all tests are passed and the green light that continues is lit. Even if only one test fails, a red light will appear on the progress bar indicating that your system (or test) has a problem.

So far, our unit tests have been simple and smooth. But how do we write tests if the method we're testing depends on an external resource, such as a file system, a database, a Web service, or something that's hard to control? To solve these problems, we need to create test stubs , pseudo-objects , and mock objects , and the next core technology will introduce them, and let's explore it with Roy Osherove's "Art of Unit Testing".

Resources

Roy Osherove, Jin Yu, "The Art of Unit Testing (2nd edition)"

Zhou Xurong

Source: http://edisonchou.cnblogs.com

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

. NET unit test Art-1. Getting Started

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.