簡體   English   中英

使用MS假冒品進行單元測試:HttpClient並等待

[英]Unit Test using MS fakes: HttpClient and await

我有創建HttpClient實例並調用某些方法並以異步模式返回響應的類。

對於ReadAsAsync,我使用了nuget包“ System.Net.Http.Formatting”。

源代碼:

    public class MyClass
    {
        readonly HttpClient client = new HttpClient();       
        public MyClass()
        {
             string myUrl = ConfigurationManager.AppSettings["MyWebAPI"];
             client.BaseAddress = new Uri(myUrl);
        }
        public async Task<List<YourClass>> GetYourClass()
        {
            var filters = "string";
            HttpResponseMessage response = await client.GetAsync(filters).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var notes = await response.Content.ReadAsAsync<List<YourClass>>();
                return notes;
            }
            return null;
        }
    }
    public class YourClass
    {
        private string Address { get; set; }

        public YourClass(string address)
        {
            Address = address;
        }       
    }

單元測試:

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            using (ShimsContext.Create())
            {
                MyClass obj = new MyClass();
                ShimHttpClient shimHttpClient = new ShimHttpClient();
                ShimHttpClient.Constructor = (t) =>
                {
                    shimHttpClient = new ShimHttpClient();
                    shimHttpClient.GetAsyncString = (a) =>
                    {
                        return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
                    };
                };
                var returnVal = obj.GetYourClass();
            }
        }

        private System.Net.Http.HttpResponseMessage function1()
        {
            return new System.Net.Http.HttpResponseMessage();
        }
    }

我們無法更改源代碼。 但需要通過虛擬調用測試對GetAsync和ReadAsAync調用進行單元測試。

聲明您的測試要異步運行並等待源類的響應

[TestMethod]
public async Task TestMethod1()
{
    using (ShimsContext.Create())
    {
        MyClass obj = new MyClass();
        ShimHttpClient shimHttpClient = new ShimHttpClient();
        ShimHttpClient.Constructor = (t) =>
        {
            shimHttpClient = new ShimHttpClient();
            await shimHttpClient.GetAsyncString = (a) =>
            {
                return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
            };
        };
        var returnVal = await obj.GetYourClass();
        Assert.IsNotNull(returnVal);
        //make more assertations on the returnVal 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM