Unit test in. Net project

Time:2021-2-5

Unit test in. Net project

Intro

“Programmers who can’t write unit tests are not qualified programmers, and programmers who don’t write unit tests are not good engineers.”

——A bad ape who wants to be a good programmer.

So the question is, what is unit testing and how to do it.

unit testing

Definition of unit test

According to Wikipedia, unit testing, also known as module testing, is a kind of testing work to verify the correctness of program module (the smallest unit of software design). Program unit is the smallest testable part of an application. In object-oriented programming, the smallest unit is method, including methods in base class, abstract class, or derived class (subclass). According to popular understanding, a unit test determines the behavior of a specific method under a specific field condition, such as Fibonacci sequence algorithm, bubble sorting algorithm.

Unit testing is to check and verify the smallest testable unit in software. For the meaning of unit in unit testing, generally speaking, we should judge its specific meaning according to the actual situation, such as unit in C language refers to a function, unit in Java refers to a class, and graphic software can refer to a window or a menu, etc. In general, the unit is the smallest function module to be tested. Unit testing is the lowest level of testing activities in the process of software development. The independent unit of software will be tested in isolation from other parts of the program.

——Baidu Encyclopediahttp://baike.baidu.com/view/106237.htm

Benefits of unit testing

  1. It is a verification behavior

    Every function in the program is tested to verify its correctness.

  2. It’s a design behavior

    Writing unit tests will allow us to observe and think from the caller. In particular, test first forces us to design the program to be easy to call and testable, which is conducive to the decoupling and modularization of the program.

  3. It’s an act of documentation

    Unit testing is an invaluable document, which is the best document to show how a function or class is used. This document is compiled, runnable, and up-to-date, always in sync with the code.

  4. It is regressive

    The automatic unit test avoids the regression of the code. After the completion of writing, the test can be run quickly anytime and anywhere.

  5. Efficient

    Automatic unit testing saves debugging time on development, most bugs can be tested by unit testing, and can reduce the testing time of testers. Sometimes by writing unit tests, you can better improve the logic of your program and make it better.

    ——Advantages of unit testinghttp://jingyan.baidu.com/article/d713063522ab4e13fdf47533.html

Principles of unit testing

  • Repeatable
  • Continue to be valid for a long time and return consistent results
  • Run in memory without external dependent components (such as real database, real file storage, etc.)
  • Quick return results
  • A test method tests only one problem

Test framework in. Net

The popular test frameworks include MS test (vs test), NUnit and xUnit

MS Test

The main classes of vs unit test are assert, stringassert and collectionassert. Please refer toMSDNintroduce

Sometimes we need to initialize the data or configuration used in the test method. There are several special test methods.

If you need to perform only one initialization iteration for all virtual users in the test, use theTestInitializeAttribute

The operation sequence of initialization method is as follows:

  1. useAssemblyInitializeAttributeThe method of marking.
  2. useClassInitializeAttributeThe method of property marking.
  3. useTestInitializeAttributeThe method of property marking.
  4. useTestMethodAttributeThe method of property marking.

When using vs test, we first need to mark the class of the test methodTestClassThe test method is marked asTestMethod

NUnit

NUnit test framework is similar to MS test

Some are in NUnit, but not in MS test framework

Assert.IsNaN/Assert.IsEmpty/Assert.IsNotEmpty/Assert.Greater/Assert.GreaterOrEqualetc.

If you want to use vs test and NUnit at the same time, you can use macros to distinguish different test frameworks, for example:

#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Category = Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestContext = System.Object;
using ClassCleanup = NUnit.Framework.TestFixtureTearDownAttribute;
using ClassInitialize = NUnit.Framework.TestFixtureSetUpAttribute;
#endif

You can see from the above that NUnit is very similar to vs test in many things, such as declaring test classes, test methods, initialization methods, etc

XUnit

XUnit is another testing framework. I think xUnit testing is more concise. There is no need to mark a separate method for initializing and releasing resources. Initialization is directly placed in the construction method, and resource release is implementedIDisposableInterface, inDisposeCompared with MS test (vs test) and NUnit, xUnit is more convenient, and it is more convenient forAssert, xUnit is more concise, for example: in MS testAssert.IsNull(null);/Assert.IsTrue(1 == 1);In xUnit, it isAssert.Null(null);/Assert.True(1 == 1);Although it looks similar, you will find xUnit more concise if you write more.

XUnit does not need to mark the type of test methodTestClass, just mark on the test methodFactOr data-drivenTheory

Basic use of xUnit

Using xUnit to write test methods can make the test code more concise and simpler. It is recommended to use xUnit to test your own code

Test example:

public class ResultModelTest
{
    [Fact]
    public void SuccessTest()
    {
        var result = ResultModel.Success();
        Assert.Null(result.ErrorMsg);
        Assert.Equal(ResultStatus.Success, result.Status);
    }

    [Theory]
    [InlineData(ResultStatus.Unauthorized)]
    [InlineData(ResultStatus.NoPermission)]
    [InlineData(ResultStatus.RequestError)]
    [InlineData(ResultStatus.NotImplemented)]
    [InlineData(ResultStatus.ResourceNotFound)]
    [InlineData(ResultStatus.RequestTimeout)]
    public void FailTest(ResultStatus resultStatus)
    {
        var result = ResultModel.Fail("test error", resultStatus);
        Assert.Equal(resultStatus, result.Status);
    }
}

The most basic test, usingFactMark test method, usingAssertTo assert your expectations of the outcome

have access toTheoryTo specify a batch of data to test, to achieve test data-driven test, simple data can be passedInlineDataIt can also be specified directlyMemberDataTo specify a method to return data for testing, or to customize a method inherited fromDataAttributeData provider for

More

I think testing is a very important part in our development process. An important indicator of high-quality projects is test coverage. A high-quality open source project must have a relatively complete test project, so it is very necessary to understand the test and integrate it into our own projects to continuously ensure the high quality of the project, and improve the test results It is also very beneficial for project refactoring, which can largely detect whether there are some destructive changes.

All in all, start writing unit tests and work hard to be a good engineer~~

Reference