1. 程式人生 > >使用xunit對asp.net core webapi進行集成測試

使用xunit對asp.net core webapi進行集成測試

rtu sharp task 技術 分離 bubuko 們的 this eba

新項目我們采用前後端分離,後端采用asp.net core webapi, 如何對後端代碼進行自動化測試呢,有以下幾種方案:

1. 單元測試,目前這個方案對我們來說難度很大,拋開時間的問題,單元測試對開發人員的水平要求很高,暫且不提。

2. 使用postman等第三方工具,模擬http請求對webapi進行測試。缺點就是webapi必須跑起來,不能像單元測試一樣,點一個按扭就可以跑測試。

3. 使用xunit等單元測試工具對webapi進行測試,為了解決postmam問題,我們使用xunit對webapi進行類單元測試。

使用xunit等單元測試工具對webapi進行測試的主要思路:

1. 使用代碼啟動webapi項目,就像program.cs中代碼一樣

2. 借助http工具類庫對webapi發送http請求,這裏我們使用RestSharp,詳見官網:http://restsharp.org/。

3. 接收返回值,進行斷言判斷,我們使用的Shouldly框架。

下面是具體的代碼:

首先創建測試項目,這是visual studio 2017自帶的xunit的測試項目,足可以看到ms的誠意了。

技術分享圖片

然後我們創建一個類,用於啟動webapi:

public class ApiServerRunning : IDisposable
    {
        
private IWebHost _builder; public void Dispose() { _builder?.Dispose(); } public void GivenRunningOn(string url) { _builder = new WebHostBuilder() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup
<Startup>() .Build(); _builder.Start(); } }

然後我們就碰到一個問題,什麽時候啟動webapi,不是每個單元測試都要啟動一次,不是運行每個類都啟動一次,而是整個測試項目只運行一個,這裏就用到了xunit的ICollectionFixture,

想具體了解的話,請自行百度。這裏就直接上代碼了:

/// <summary>
    /// used to startup weiapi, run only once
    /// </summary>
    public class TestFixture : IDisposable
    {
        public ApiServerRunning _server = new ApiServerRunning();

        public TestFixture()
        {
            this.Given(s => _server.GivenRunningOn(TestConst.SERVER_URL))
                .Then(x => x.Connect())
                .BDDfy();

        }
        private void Connect()
        {
            Console.WriteLine("webapi startup successfully!!! ");
        }

        public void Dispose()
        {
        }
    }
    /// <summary>
    /// used to tag every class using test fixture
    /// </summary>
    [CollectionDefinition("TestCollection")]
    public class TestCollection:ICollectionFixture<TestFixture>
    {
    }

有了以上兩個類,我們接下來就可以寫單元測試了:

[Collection("TestCollection")]
    public class TaskControllerTest : TestBase
    {
        [Fact(DisplayName = "獲取列表")]
        private void GetOpinionTaskHospitals_Test()
        {
            var req = agent.CreateRequest("GetTasks")
                .AddParameter("month", "2015-07-01")
                .AddHeader(FmConsts.HeaderName_UserInfo, TestConst.USER_INFO);

            var rel = agent.Execute<<List<Task>>>(req);

            rel.Result.Count.ShouldNotBe(0);

        }
    }

每個類都發送請求,所以這裏有個TestBase的基類,裏面有一個agent的http的對象,是我們封閉了restsharp的http請求對象,這裏就不貼了。

還有如果沒有登錄,所有如果想使用登錄的cookie,這裏我是直接添加了一個頭信息,相當於一個登錄,但是這裏肯定有問題可能會過期,當然辦法總比困難多。

還有一個難點,就是這裏的測試,還是用的我們的開發數據庫,這個測試會汙染數據,由於開發數據的變量,也會影響測試結果,如果替換開發數據庫oracle為內存數據為庫,而且代碼變動也很少,是我們接下來的工作。 請經驗的同學,請指教。

使用xunit對asp.net core webapi進行集成測試