当前位置:网站首页>ASP dotnet core does integration test based on TestServer
ASP dotnet core does integration test based on TestServer
2022-04-21 11:42:00 【lindexi】
I have an old dotnet core 3.1 Of asp dotnet core project , Now I'm going to upgrade him to dotnet 5 了 . But I don't want to roll over like a blog Park , So I need to do some assistance in integration testing , Although the car still overturned , But I want to learn the great spirit of blog Garden , Write down the methods of all automated test projects done in this project
At the beginning, from dotnet core 3.1 Upgrade to dotnet 5 Before , I'll start preparing for integration testing . The first test to prepare is to turn on the host , Then call... Over the network . However, as soon as this method was opened, I was dragged out …… Because opening the host will occupy the port , It happens that several of my projects use the same port
And I started to try to specify random ports in the configuration file , At this time, there is the network authority of metaphysics , But I don't know who to drag out
At this time, my partner gave me Amway TestServer library , Through this library, you can not listen to ports , All running in memory . Yes, of course , Accessing external services depends on injecting , I still go online without injection . It's just that your application won't listen to the port
Start with a new project , This is a unit test project , For integration testing
stay dotnet The inside routine is to install NuGet package , And then call . Installed NuGet yes Microsoft.AspNetCore.TestHost library . This library needs to be installed at the beginning 3.1.10 Version of , After that, the project is upgraded to dotnet 5 To use the latest version
<
PackageReference
Include=
"Microsoft.AspNetCore.TestHost"
Version=
"3.1.10"
/>
- 1.
The libraries installed in my unit test project are as follows
<
ItemGroup
>
<
PackageReference
Include=
"Microsoft.NET.Test.Sdk"
Version=
"16.8.0"
/>
<
PackageReference
Include=
"MSTest.TestAdapter"
Version=
"2.1.1"
/>
<
PackageReference
Include=
"MSTest.TestFramework"
Version=
"2.1.1"
/>
<
PackageReference
Include=
"coverlet.collector"
Version=
"1.3.0"
/>
<
PackageReference
Include=
"Moq"
Version=
"4.15.1"
/>
<
PackageReference
Include=
"MSTest.TestAdapter"
Version=
"2.1.2"
/>
<
PackageReference
Include=
"MSTest.TestFramework"
Version=
"2.1.2"
/>
<
PackageReference
Include=
"MSTestEnhancer"
Version=
"2.0.1"
/>
<
PackageReference
Include=
"System.Text.Encoding.CodePages"
Version=
"5.0.0"
/>
<
PackageReference
Include=
"Microsoft.AspNetCore.TestHost"
Version=
"3.1.10"
/>
</
ItemGroup
>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
In the use of TestServer During integration testing , In fact, it is to replace the logic of starting the host , Such as ASP.NET Core Build a multi tier website architecture 【12-xUnit Integration test of unit test 】 The method described in this blog , Let's create a new static class , Used to create hosts and run
[TestClass]
public static class TestHostBuild
{
public static HttpClient GetTestClient() => _host.GetTestClient();
[AssemblyInitialize]
public static async Task GlobalInitialize(TestContext testContext)
{
IHost host = await CreateAndRun();
_host = host;
}
private static IHost _host;
[AssemblyCleanup]
public static void GlobalCleanup()
{
_host.Dispose();
}
private static Task
<
IHost
> CreateAndRun() => CreateHostBuilder().StartAsync();
public static IHostBuilder CreateHostBuilder() =>
Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup
<
Startup
>();
webBuilder.UseTestServer(); // The key is to build more of this line TestServer
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
// Configuration for testing
var appConfigurator = config.ToAppConfigurator();
// It's used here https://github.com/dotnet-campus/dotnetCampus.Configurations Configuration
var apmConfiguration = appConfigurator.Of
<
ApmConfiguration
>();
apmConfiguration.DisableApm = true;
})
// Use auto fac Instead of default IOC Containers
.UseServiceProviderFactory(new AutofacServiceProviderFactory());
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
In the above code CreateHostBuilder and asp dotnet core Project Program.cs The code is almost , It's just ConfigureWebHostDefaults Method changed
and ConfigureAppConfiguration Yes, configure , Here are some test items specially configured , If you disable my APM service . When doing integration testing , You can choose to turn on or off APM service , If your o & M partner won't hit you , So let's start APM better . The code here uses https://github.com/dotnet-campus/dotnetCampus.Configurations To configure
stay MSTest In the unit test project , Use AssemblyInitialize characteristic , You can let a static method run once when the unit test starts . While using AssemblyCleanup Methods can be used after the unit test is completed , It will be called once whether it is successful or not
So in GlobalInitialize Method marker AssemblyInitialize characteristic , Create a host here and run the host . At this time, the running host will not listen to the port , Therefore, it cannot be called in the form of port , It needs to be used TestServer Get the method provided by HttpClient To visit . That is, through TestHostBuild.GetTestClient Only when you get it can you access the host in memory
I create a test file for each controller , For unit testing
For example, there is one in my project StatusOverviewController controller , This controller is used to return the contents of the service , The general logic is as follows
[ApiController]
[Route("[controller]")]
[Route("/")]
public class StatusOverviewController : ControllerBase
{
[HttpGet]
public string Get()
{
// Maybe use DateTimeOffset More halal , But I didn't write it
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
Create a new unit test to test the access of this interface
[TestClass]
public class StatusOverviewControllerTest
{
[TestMethod]
public async Task GetTest()
{
using var httpClient = TestHostBuild.GetTestClient();
var result = await httpClient.GetStringAsync("/");
Assert.IsNotNull(result);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
Maybe this will complete the test of this interface
Of course, this is for simple interfaces, which can be written like this , But for complex interfaces , There are many special needs , You need to use CUnit The library , Through installation MSTestEnhancer This NuGet Library, you can add unit test auxiliary Library , Like the following code
<
PackageReference
Include=
"MSTestEnhancer"
Version=
"2.0.1"
/>
- 1.
After installation , You can write the following logic
[TestClass]
public class DemoTest
{
[ContractTestCase]
public void Foo()
{
" When satisfied A When the conditions , It should happen A' things .".Test(() =>
{
// Arrange
// Action
// Assert
});
" When satisfied B When the conditions , It should happen B' things .".Test(() =>
{
// Arrange
// Action
// Assert
});
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
This CUnit stay GitHub Open source , Please have a look at https://github.com/dotnet-campus/CUnit
After the integration test project is ready , I started preparing to upgrade to dotnet 5 了 , However, at this time, it was found that the build server overturned , Such as I just rolled back from the server dotnet 5 Environment Blog content
Finally I passed How to give CI CD On the server .NET 5 Build and run the environment The method has been repaired
However, my little friend told me from dotnet core 3.1 To dotnet 5 There are the following changes Breaking changes, version 3.1 to 5.0 - .NET Core
After two days of update still failed , I forced magic to change the code , Up to dotet 5 after , Found out APM Hang up …… because APM The original... Is used internally dotnet core 3.1 The in dotnet 5 Abandoned interface …… Then it's time to blog
I set up my own blog https://blog.lindexi.com/ Welcome to , There are a lot of new blogs in it .
If you see anything in the blog that you don't understand , Welcome to exchange , I built it. dotnet Vocational and technical college Welcome aboard
This work adopts the signature of knowledge sharing - Noncommercial use - Share in the same way 4.0 International license agreement to license . Welcome to reprint 、 Use 、 Re release , But be sure to keep the article signed by Lin Dexi , Not for commercial purposes , Based on this revised work must be released with the same license . If you have any questions , Please contact me .
版权声明
本文为[lindexi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211109376917.html
边栏推荐
- MQ相關流程及各項內容
- Xinghan future cloud native basic governance platform schedulx v1 1.0 heavy release to help enterprises reduce costs and increase efficiency
- No supported authentication methods available
- How to carry cookies in cross domain requests?
- L3-028 森森旅游 (30 分) (dijkstra+反向建图+细节)
- JSTL -- JSP 标准标签库
- 3年产品经理,从5k到30k,我是这样成长的(上)
- Normalized records in pycharm
- Basic logic summary of (line test) graphic reasoning questions in [recruitment evaluation questions] (with examples)
- 手撕链表题,我看你也行(1)
猜你喜欢

华为、海尔智家、小米都在做的全屋智能,全在哪?

Nocalhost for dapr remote debugging

Introduction to Alibaba's super large-scale Flink cluster operation and maintenance system

离线强化学习(Offline RL)系列4:(数据集) 经验样本复杂度(Sample Complexity)对模型收敛的影响分析

Leetcode1615. 最大网络秩(medium,图论基础)

Solution | fast intercom dispatching system: efficient cooperation

常见工具 nc Wireshark反弹shell

How to carry cookies in cross domain requests?

Redis interview questions

阅读材料:信息技术年谱
随机推荐
Normalized records in pycharm
1.精准营销实践阿里云odpscmd精准营销数据处理
星汉未来云原生基础治理平台SchedulX V1.1.0 重磅发布,助力企业降本增效
L2-001 紧急救援 (25 分)(dijkstra综合应用)
AES encryption and decryption with cryptojs
粉笔科技推行OMO一体化模式 双核驱动营收快速增长
New features of ES6 (7): proxy proxy / model module / import / export
Dynamics CRM 365 reports an error when calling the external interface in plugins: Request 'system Net. Permission of type 'webpermission, system, version = 4.0.0.0, culture = neutral, publickey = b77a
pycharm中归一化记录
连接服务器报错No supported authentication methods available
开源文化依旧熠熠生辉 —— 在openEuler社区,有技术、有idea,你就是主角
Chrome开发者工具详解 一
L2-004 这是二叉搜索树吗? (25 分)
OV代码签名和EV代码签名证书区别
JSTL -- JSP standard tag library
Leetcode daily question: 824 Goat Latin
org. apache. flink. client. deployment. ClusterDeploymentException: Could not deploy Yarn job cluster.
如何求源码,反码,补码
解决方案| 快对讲调度系统:高效协作
L2-039 清点代码库 (25 分)