This tutorial takes you through an interactive experience building a sample solution step-by-step to learn unit testing concepts. If you prefer to follow the tutorial using a pre-built solution, view or download the sample code before you begin. For download instructions, see Samples and Tutorials.
This article is about testing a .NET Core project. If you're testing an ASP.NET Core project, see Integration tests in ASP.NET Core.
Open a shell window. Create a directory called unit-testing-using-mstest to hold the solution. Inside this new directory, run dotnet new sln to create a new solution file for the class library and the test project. Create a PrimeService directory. The following outline shows the directory and file structure thus far:
Make PrimeService the current directory and run dotnet new classlib to create the source project. Rename Class1.cs to PrimeService.cs. Replace the code in the file with the following code to create a failing implementation of the PrimeService class:
C#
using System;
namespacePrime.Services
{
publicclassPrimeService
{
publicboolIsPrime(int candidate)
{
thrownew NotImplementedException("Please create a test first.");
}
}
}
Change the directory back to the unit-testing-using-mstest directory. Run dotnet sln add to add the class library project to the solution:
.NET CLI
dotnetslnadd PrimeService/PrimeService.csproj
Create the test project
Create the PrimeService.Tests directory. The following outline shows the directory structure:
Make the PrimeService.Tests directory the current directory and create a new project using dotnet new mstest. The dotnet new command creates a test project that uses MSTest as the test library. The template configures the test runner in the PrimeServiceTests.csproj file:
The test project requires other packages to create and run unit tests. dotnet new in the previous step added the necessary MSTest packages and tools for code coverage reporting.
Add the PrimeService class library as another dependency to the project. Use the dotnet add reference command:
Write a failing test, make it pass, then repeat the process. Remove UnitTest1.cs from the PrimeService.Tests directory and create a new C# file named PrimeService_IsPrimeShould.cs with the following content:
C#
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prime.Services;
namespacePrime.UnitTests.Services
{
[TestClass]
publicclassPrimeService_IsPrimeShould
{
privatereadonly PrimeService _primeService;
publicPrimeService_IsPrimeShould()
{
_primeService = new PrimeService();
}
[TestMethod]
publicvoidIsPrime_InputIs1_ReturnFalse()
{
bool result = _primeService.IsPrime(1);
Assert.IsFalse(result, "1 should not be prime");
}
}
}
Save this file and execute dotnet test to build the tests and the class library and then run the tests. The MSTest test runner contains the program entry point to run your tests. dotnet test starts the test runner using the unit test project you've created.
Your test fails. You haven't created the implementation yet. Make this test pass by writing the simplest code in the PrimeService class that works:
C#
publicboolIsPrime(int candidate)
{
if (candidate == 1)
{
returnfalse;
}
thrownew NotImplementedException("Please create a test first.");
}
In the unit-testing-using-mstest directory, run dotnet test again. The dotnet test command runs a build for the PrimeService project and then for the PrimeService.Tests project. After building both projects, it runs this single test. It passes.
Add more features
Now that you've made one test pass, it's time to write more. There are a few other simple cases for prime numbers: 0, -1. You could add new tests with the TestMethod attribute, but that quickly becomes tedious. There are other MSTest attributes that enable you to write a suite of similar tests. A test method can execute the same code but have different input arguments. You can use the DataRow attribute to specify values for those inputs.
Instead of creating new tests, apply these two attributes to create a single data driven test. The data driven test is a method that tests several values less than two, which is the lowest prime number. Add a new test method in PrimeService_IsPrimeShould.cs:
C#
[TestMethod]
[DataRow(-1)]
[DataRow(0)]
[DataRow(1)]
publicvoidIsPrime_ValuesLessThan2_ReturnFalse(intvalue)
{
var result = _primeService.IsPrime(value);
Assert.IsFalse(result, $"{value} should not be prime");
}
Run dotnet test, and two of these tests fail. To make all of the tests pass, change the if clause at the beginning of the IsPrime method in the PrimeService.cs file:
You've built a small library and a set of unit tests for that library. You've structured the solution so that adding new packages and tests is part of the normal workflow. You've concentrated most of your time and effort on solving the goals of the application.
Bạn có thể tìm thấy nguồn cho nội dung này trên GitHub, nơi bạn cũng có thể tạo và xem lại các vấn đề và yêu cầu kéo. Để biết thêm thông tin, hãy xem hướng dẫn dành cho người đóng góp của chúng tôi.
Ý kiến phản hồi về .NET
.NET là một dự án nguồn mở. Chọn liên kết để cung cấp ý kiến phản hồi:
Tham gia chuỗi buổi gặp gỡ để xây dựng các giải pháp AI có thể mở rộng dựa trên các trường hợp sử dụng trong thế giới thực với các nhà phát triển và chuyên gia đồng nghiệp.
Bắt đầu kiểm tra ứng dụng C# của bạn bằng cách sử dụng các công cụ kiểm tra trong Visual Studio. Tìm hiểu cách viết bài kiểm tra, sử dụng Trình khám phá Kiểm tra, tạo bộ bài kiểm tra và áp dụng mô hình tái bản màu đỏ, màu lục để viết mã.
Xây dựng các giải pháp toàn năng trong Microsoft Azure để tạo Azure Functions, triển khai và quản lý các ứng dụng web, phát triển các giải pháp sử dụng bộ nhớ Azure và hơn thế nữa.