Unit Test
This article will be based on an example of this series demonstrating how to use Xunit in ASP. MOQ for unit testing, and integration testing of the entire project.
The first part, XUnit
Modify the contents of the Project.json file, add Xunit related NuGet package references, and modify the partial configuration.
1 {2 "version": "1.0.0-*", 3 "Testrunner": "Xunit",//Set Test tool for Xunit 4 5 "Buildoptions": {6 "Debugtype": "Po Rtable ", 7" Emitentrypoint ": True 8}, 9" dependencies ": {ten" Microsoft.NETCore.App ": {One" type ":" PLATF ORM "," Version ":" 1.0.0 "},14" Microsoft.AspNetCore.Server.Kestrel ":" 1.0.0 "," Microsoft.aspnetcor " E.mvc ":" 1.0.0 "," Microsoft.Extensions.Logging ":" 1.0.0 "," Microsoft.Extensions.Logging.Console ":" 1.0.0 ", 18 "Microsoft.Extensions.Logging.Debug": "1.0.0", "Microsoft.Extensions.Logging.Filter": "1.0.0", "Nlog.extens" Ions. Logging ":" 1.0.0-rtm-alpha2 "," Autofac.Extensions.DependencyInjection ":" 4.0.0-rc3-309 "," Microsoft.extensions " . Configuration ":" 1.0.0 "," Microsoft.Extensions.Configuration.FileExtensions ":" 1.0.0 "," MICROSOFT.EXTENSIONS.C " Onfiguration. Json ":" 1.0.0 "," Microsoft.Extensions.Options.ConfigurationExtensions ":" 1.0.0 "," Xunit ":" 2.2.0-beta2-build33 00 ", 27 "Dotnet-test-xunit": "2.2.0-preview2-build1029"},29 "frameworks": {"netcoreapp1.0": {31//Set Compatibility box "Imports": ["Dotnet54", "Portable-net45+win8" 35]36}37}38}
Add a demo class and a test class
1 namespace Webapiframe 2 {3 Public class Demomodel 4 {5 public int Add (int a, int b) 6 {7 return a + b; 8 } 9 public bool isodd (int num) One {ten return num% 2 = = 1;13 }14 }15}
1 using Xunit; 2 3 Namespace Webapiframe.test 4 {5 Public class Demomodeltest 6 {7 private readonly Demomodel _demo ; 8 9 Public demomodeltest () { _demo = new Demomodel (); }13 [fact]15 public void Addtest () + {+ int result = _demo. ADD (1, 2); assert.equal (3, result); }20 }21}
Open the cmd window, go to the project root directory, enter the command dotnet test, the unit test will start, you can view the test results in the output
Add unit test code to another method
1 [Theory]2 [Inlinedata (1)]3 [Inlinedata (2)]4 [Inlinedata (3)]5 public void isodd (int num) 6 {7 bool result = _demo. IsOdd (num); 8 assert.true (result, $ "{num} is not odd."); 9 }
Start unit tests again to view test results
The result shows that four unit test cases were executed and one failed.
By comparing the two test methods above, you can see that the parameter list for the test method is different, depending on the identity of the attribute being used.
The [face] attribute identifies a test case that represents a fixed input, whereas the [theory] attribute identifies a test case that can specify multiple inputs, combined with the Inlinedata attribute identification. In the above example, a total of three inlinedata feature identifiers are used, each setting has a different value, and when the unit test is executed, the set value is assigned by the test framework to the parameters of the corresponding test method.
Part II, MOQ
In the previous example, the following interfaces and classes have been defined
IUserRepository.csUsersController.cs
We are going to unit test the UsersController.cs method, while the Userrepository instance is injected through the constructor dependency, so we need to use MOQ to simulate the generation of this instance.
Before introducing the MOQ package, you need to modify the Nuget.config configuration file to increase the package source address.
Nuget.config configuration file path: c:\users\{user}\appdata\roaming\nuget
1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <configuration> 3 <activePackageSource> 4 < Add key= "nuget.org" value= "https://www.nuget.org/api/v2/"/> 5 </activePackageSource> 6 < Packagesources> 7 <add key= "nuget.org" value= "Https://api.nuget.org/v3/index.json" protocolversion= "3"/ > 8 9 <!--increased package source address-->10 <add key= "Aspnet-contrib" value= "https://www.myget.org/F/ Aspnet-contrib/api/v3/index.json "/>11 </packagesources>12 </configuration>
Introducing MOQ-related NuGet packages: " moq.netcore": "4.4.0-beta8"
Adding a unit test class
1 using System.Collections.Generic; 2 using System.Linq; 3 using MICROSOFT.ASPNETCORE.MVC; 4 using Moq; 5 using Webapiframe.controllers; 6 using Webapiframe.models; 7 using Webapiframe.repositories; 8 using Xunit; 9 namespace Webapiframe.test11 {public class UsersControllerTest13 {readonly Userscontrol Ler _controller;15 Public userscontrollertest () ~ {var Mockrepo = new Mock<iuserrepos Itory> (); Mockrepo.setup (repo = repo. GetAll ()). Returns (Getusers ()); _controller = new Userscontroller (mockrepo.object);}22 [fact]24 public void Getalltest () {Iactionresult ActionResult = _controller. GetAll (); var objectresult = assert.istype<objectresult> (actionresult); var result = the Ert. Isassignablefrom<ienumerable<user>> (Objectresult.value); Assert.equal (3, result. Count ()); 30}31-Private Ienumerable<user> Getusers () () {Return to New list<user> () 35 {$ new User () {id = 1, name = "Name:1", Sex = "Male"},37 new User () {id = 2, name = "Name:2", sex = "Female"},38 new User () {Id = 3, name = "Name:3", sex = "Male"},39};40 }41}42}
Perform unit tests in the CMD window to view test results
In a well-structured project, each layer relies on a pre-agreed interface. In multi-person collaborative development, most people will only be responsible for their own part of the module function, development progress is often inconsistent. While other modules that a developer relies on to unit-test their modules have not yet been developed, it is necessary to provide impersonation capabilities to the dependent interfaces by mocking them to complete the unit testing of their modules without actually relying on the specific functionality of the other modules.
Part III, integration testing
The above example is just a unit test of logic. For an ASP. NET Core project, you also need to simulate testing each request portal in the context of site deployment. This is usually done with tools such as Fiddler, which you can also do programmatically in. Net Core.
First, the NuGet packages required for testing are introduced. Because we are testing the Webapi interface, the response content is a JSON-formatted string, so we also need to reference the JSON serialized NuGet package.
"Microsoft.AspNetCore.TestHost": "1.0.0", "Newtonsoft.json": "9.0.1"
To add a test class
1 using System.Collections.Generic; 2 using System.Net.Http; 3 using System.Threading.Tasks; 4 using Microsoft.AspNetCore.Hosting; 5 using Microsoft.AspNetCore.TestHost; 6 using Newtonsoft.json; 7 using Webapiframe.models; 8 using Xunit; 9 namespace Webapiframe.test11 {public class WebApiFrameTest13 {readonly testserver _serv er;15 private readonly HttpClient _client;16 webapiframetest public _server () = new TestServer (new Webhostbuilder (). Usestartup<startup> ()); _client = _server. CreateClient ();}22 [fact]24 Public async Task getalltest () * + var res Ponse = await _client. Getasync ("/api/users"); response. Ensuresuccessstatuscode (); var responsestring = await response. Content.readasstringasync (); ilist<user> users = Jsonconvert.deserializeobject<ilist<user>> ;(responsestring); 31 32 Assert.equal (3, users. Count);}34 [theory]36 [Inlinedata (1)]37 [Inlinedata (2)]38 [Inlinedata (3)]39 Public async Task gettest (int id)-{$ var response = await _client. Getasync ($ "/api/users/{id}"); response. Ensuresuccessstatuscode (); responsestring var = await response. Content.readasstringasync (); User user = Jsonconvert.deserializeobject<user> (responsestring); 46 47 Assert.notnull (user); 48}49}50}
Perform unit tests in the CMD window to view test results
In the example above, the communication between the server side (TestServer) and the client (HttpClient) is simulated at the same time in a project, thus achieving the goal of the overall test Webapi interface.
Net Core WEBAPI Unit Testing