DotNetCore跨(kua)平臺(tai)~功能測試TestHost的使(shi)用(yong)
之(zhi)前寫了關(guan)于自動化測試(shi)的(de)相關(guan)文(wen)章,包(bao)括gitlab,unittest,jenkins pipeline等,基于都是功能(neng)點的(de)測試(shi),當我們(men)的(de)框架或(huo)者業務修(xiu)改(gai)之(zhi)后,需(xu)要走一(yi)篇自動化測試(shi),以此來(lai)保證我們(men)的(de)修(xiu)改(gai)過(guo)的(de)功能(neng)是正確的(de),而(er)今天(tian)主(zhu)要說一(yi)下流程(cheng)(cheng)測試(shi),從(cong)api網站的(de)入口,從(cong)一(yi)個請求開始到結(jie)束這個過(guo)程(cheng)(cheng),我們(men)可以通過(guo)TestHost來(lai)完成!
一個完整的流程化測試需要經過以下幾個步驟:
- 建立xunit項目
- 引用需要測試的api項目
- 添加WebFixture攔截器,注意其中的startup是指api項目的,建立測試使用的TestServer和HttpClient
- 在xunit里使用HttpClient即可
一 建立xunit項目

二 引(yin)用需要(yao)測試的api項目

三 添加WebFixture攔截器,注意其中(zhong)的(de)(de)startup是指(zhi)api項目的(de)(de),建立測試使用的(de)(de)TestServer和HttpClient
/// <summary> /// Web攔(lan)截器 /// </summary> public class WebFixture { public TestServer Server; public HttpClient Client; public WebFixture() { var hostBuilder = new WebHostBuilder(); var Server = new TestServer(hostBuilder.UseStartup<Lind.DotNetCore.RepositoryTest.Startup>()); this.Client = Server.CreateClient(); } }
四 在xunit里(li)使用HttpClient即可
[Fact] public void TestLindDotNetCoreRepositoryTest() { var msg = _webFixture.Client.GetAsync("/dapper") .Result .Content .ReadAsStringAsync() .Result; Assert.NotNull(msg); }
這樣,一個流程(cheng)化測試的(de)例(li)子就完成了,還(huan)是比較簡單的(de)!
關(guan)鍵在于找到這種測試的(de)方法!