Today we are developing a ASP.NET Web API When a project writes unit tests , I can't stand the stupid way before , Decided to reform .
Before Web API The following operations are required for unit testing of :
Initial configuration :
1) stay IIS Create a site to specify Web API project
2) stay hosts Plus the site's IP Address resolution
Every time you change the code :
3) After modifying the code, press F6 compile
4) use TestDriven.Net Run unit tests
You can see that this method is good 、 How stupid 、 It's a pain in the neck . The ideal way is : No initial configuration is required , After modifying the code, you don't need to press F6 compile , Run unit tests directly , Complete the operation in one step .
I can't stand the old way today 、 Can't stand the temptation of the ideal way , Determined to solve this problem , Finally through Owin Host Realized , Share it through this blog post .
use Owin Host The idea of implementation is very simple , It's in unit testing with Owin Host function ASP.NET Web API Site , Then the unit test code directly requests this Owin Host Site for testing .
our Web API The project is based on ASP.NET 4.5 + ASP.NET Web API 5.2.3 Developed , No, OWIN Related code , So we have to start with Web API Add some code to the project , In order to let Owin Host Can load .
First nuget install Owin bag (IAppBuilder In this bag ):
PM> Install-Package Owin
Then add Startup.cs:
public class Startup
{
public void Configuartion(IAppBuilder app)
{
}
}
next nuget install Microsoft.AspNet.WebApi.Owin bag (app.UseWebApi The extension method is in this package )
PM> Install-Package Microsoft.AspNet.WebApi.Owin
stay Startup.Configuratrion Method , call WebApiConfig.Register Method ( This has been achieved before , Routing configuration is one of them ) To configure HttpConfiguration, Then register it to OWIN In the pipeline .
public class Startup
{
public void Configuration(IAppBuilder app)
{
var configuraton = new HttpConfiguration();
WebApiConfig.Register(configuraton);
app.UseWebApi(configuraton);
}
}
Web API The project only needs such a simple transformation , You can support Owin Host, No side effects , Does not affect the use of IIS Deployment site .
The transformation of unit test code is also very simple , Just use it before the run test Microsoft.Owin.Hosting Medium WebApp.Start() Method loading Web API Site .
First nuget install Owin Host Bag of :
PM> Install-Package Microsoft.Owin.Hosting
PM> Install-Package Microsoft.Owin.Host.HttpListener
Then use... In the constructor of the test class WebApp.Start() start-up Web API Site :
public class CommentsWebApiTest : IDisposable
{
private const string HOST_ADDRESS = "http://localhost:8001";
private IDisposable _webApp;
public CommentsWebApiTest()
{
_webApp = WebApp.Start<Startup>(HOST_ADDRESS);
Console.WriteLine("Web API started!");
} public void Dispose()
{
_webApp.Dispose();
}
}
And then you can get out of IIS It's incredibly easy to Web API Unit test of .
Let's have a practical experience :
1) stay Web API In the project, a ApiController
public class CommentsController : ApiController
{
[Route("blogposts/{postId}/comments")]
public async Task<IHttpActionResult> Get(int postId)
{
var comments = new Comment[] { new Comment {
PostId = postId,
Body = "Coding changes the world1" } };
return Ok<Comment[]>(comments);
}
}
2) Based on Owin Host run Web API Unit test code for the site
public class CommentsWebApiTest : IDisposable
{
private const string HOST_ADDRESS = "http://localhost:8001";
private IDisposable _webApp;
private HttpClient _httClient; public CommentsWebApiTest()
{
_webApp = WebApp.Start<Startup>(HOST_ADDRESS);
Console.WriteLine("Web API started!");
_httClient = new HttpClient();
_httClient.BaseAddress = new Uri(HOST_ADDRESS);
Console.WriteLine("HttpClient started!");
} public void Dispose()
{
_httClient.Dispose();
_webApp.Dispose();
} [Fact]
public async Task GetComments()
{
var postId = ;
var response = await _httClient.GetAsync($"/blogposts/{postId}/comments");
if(response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var comments = await response.Content.ReadAsAsync<Comment[]>();
Assert.NotEmpty(comments);
Assert.Equal(postId, comments[].PostId);
Assert.Equal("Coding changes the world", comments[].Body);
}
}
notes : except nuget install Microsoft.Owin.Hosting And Microsoft.Owin.Host.HttpListener bag , And install Microsoft.AspNet.WebApi.Client bag (ReadAsAsync<Comment[]> In this bag ).
3) Run unit tests : In the unit test method, right-click and click Run Test(s)( It's using TestDriven.Net, Will compile automatically before unit testing )
4) Look at the unit test results , Verification test Web API Is the ideal way to achieve :
Output from WebApiTests.CommentsWebApiTest.GetComments:
Web API started!
HttpClient started! 1 passed, 0 failed, 0 skipped, took 4.91 seconds (xUnit.net 1.9.2 build 1705).
The test passed ! The ideal way to achieve !
This experience proves once again that , When there's a problem that affects the fun of writing code , Make up your mind to solve it as soon as possible , Otherwise, the time it wastes is probably the time it takes to solve the problem n times , And most of the time, how easy it is to solve a problem depends on how determined you are .
【 to update 】
There's a place to pay attention to , In the unit test, with owin host function web api Site time , Configuration information ( For example, a database connection string ) It's from the unit test project app.config Read from , Not from web api Project web.config Read from , So will web.config Copy the relevant configuration in to app.config in .
【 Reference material 】
ASP.NET Web API Integration Testing with One Line of Code
Development Notes : use Owin Host To break away from IIS run Web API More articles on unit testing
- use Owin Host To break away from IIS run Web API unit testing
Development Notes : use Owin Host To break away from IIS run Web API unit testing Today we are developing a ASP.NET Web API When a project writes unit tests , I can't stand the stupid way before , Decided to reform . Before Web API The list of ...
- Use Nancy.Host To break away from iis Of Web application
This article will show you how to use Nancy.Host To break away from iis Of Web application , On the open source task management platform TaskManagerV2.0 It's already used in the code Nancy.Host Realize self hosting Web application . Study Nancy It was the best before ...
- With Self Host The way to stay Web API
Common Class and entity definitions .Web API Please refer to my last article for the definition of : With Web Host The way to stay Web API. One . With Self Host I need to build a new one Console Console project (SelfHost) ...
- PCB Out of the IIS Of Web application
In use .net Web Programming , We wrote Web App preferences will be linked to IIS above , Because it's stable and functional , But it's not our only choice , Microsoft has provided us with Owin Components ,Web The host that should be can no longer be IIS 了 , With Owin after ...
- Owin asp.net Out of the IIS
http://www.cnblogs.com/jesse2013/p/owin-webserver.html
- With Web Host The way to stay Web API
One . Create a new one Common And create a new one for testing Contact Entity class namespace Common { public class Contact { public string Id { ge ...
- [ Roof placement ] Android Development Notes ( Growth track )
classification : Develop learning notes 2013-06-21 09:44 26043 Human reading Comment on (5) Collection Android Development Notes 1. Console output :called unimplemented OpenGL ES API ...
- [ turn ] JSON Web Token in ASP.NET Web API 2 using Owin
In this paper, from :http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/ ...
- JSON Web Token in ASP.NET Web API 2 using Owin
In the previous post Decouple OWIN Authorization Server from Resource Server we saw how we can separ ...
Random recommendation
- iOS Create secure singletons
Create secure singletons #import "Singleton.h" @implementation Singleton static Singleton* _instance = nil; ...
- xcode Automatically add comments , Generating documentation
One . Automatically generate comment code Add a shortcut , Generate Comment code ThisService Download link :http://wafflesoftware.net/thisservice/ ...
- About beginners uploading files to github Methods
turn :http://blog.csdn.net/steven6977/article/details/10567719 I'm ashamed to say that , I started using it recently github, Xiaobai is one , I studied all afternoon yesterday . Finally I can upload ...
- CSS: Table-Layout & Word-Break Set the width of tables and columns to be fixed
1. Set up Table The column width of is set by table width and column width ( Specify the table width , The width of each column ): table#tbl_id{table-layout:fixed;} 2. Set up TD The content is wrapped according to the width , Even if there is no ...
- Zabbix actual combat - API Tutorial (2)-- Overall architecture
- 10 Project 1: Erste Schritte in Python
10 Project 1: Erste Schritte in PythonAnimationIn den Projekten werden sie nicht nur statische Objek ...
- Navicat Premium 12 Registration machine use tutorial
Take a look at the specific installation of the software . Activate the graphic tutorial : 1. First download and install the software normally until the end : If you open it at this time , Is prompted to register 2. Run the registry tool as an administrator Navicat_Keygen_Patch[vxia.net ...
- c++ Class member function followed by const What is it for? ?
Time is something that can be caught off guard , Sunny is windy, cloudy is rainy , We can't fight day and night , Read the past again , Steal the green silk but keep a you #include <iostream> #include <string> usin ...
- Java Basics - Data types and wrapper classes
data type There are basic data types and reference data types The basic data type variable stores the data itself , A variable that references a data type is the spatial address where the data is stored Four basic data types : The logical model boolean The text type char Integer type byte s ...
- iOS: Mobile “ User feedback and customer service ” A couple of platforms SDK Introduction to
Simple explanation : The user feedback function is almost every app They all have one function point , Connect with users through feedback function . communicate , Collect user feedback and Bug The report , Communicate with users instantly , To a certain extent app Competitiveness . And give app score ...