.Net Core的簡單單元測試基於Mock和自定義


首先創建

使用mock 外部依賴一般用Mock 模擬

下載包

 例如

3.1:首先先要使用MOCk來模擬測試方法需要的參數,這一步為 Arrange;
    簡單的模擬
      var mock = new Mock<Object>();
   模擬返回的數據
  mock .Setup(x => x.方法(It.IsAny<string>()(備注這里是模擬的方法參數))).Returns(Task.FromResult(這個方法會返回的參數));

![在這里插入圖片描述](https://img-blog.csdnimg.cn/2020042810512498.png)
  
3.2:在模擬完請求參數后就要開始調用測試的方法了(ACT),傳入測試方法需要的相應參數 

![在這里插入圖片描述](https://img-blog.csdnimg.cn/20200428113817151.png)
簡單的對返回參數進行判斷
     Assert.True(httpClientInvoked);
Assert里有很多種判斷方法,可以自己慢慢看

 判斷測試方法里的子方法是否被調用,下面的方法是判斷是否至少執行一次
 mock(模擬方法名).Verify(fake => fake.AddAsync(It.IsAny<EvaluationEntity>()), Times.AtLeastOnce());
 ![在這里插入圖片描述](https://img-blog.csdnimg.cn/20200428114334530.png)

最后再說一下如果測試的方法里需要拋出錯誤怎么判斷,由於會拋異常所有要寫在一起
 //Act & Assert
        var ex = await Assert.ThrowsAsync<HFQInternalServerException>(async () => await srv.CommentAsync("tran1", "1", "1", "admin", "305", "測試留言"));
        Assert.Equal(ErrorMessages.RemarkSubmitError.ToString(), ex.Code);

![在這里插入圖片描述](https://img-blog.csdnimg.cn/20200428114442581.png)

 ,單元測試永遠都只關注需要測試的方法內部的邏輯實現,至於外部依賴方法的測試,則應該放在另一個專門針對這個方法的單元測試用例中。弄清楚這個問題,我們才能更加理解另一個單元測試不可缺少的框架——Mock框架,在我們寫的測試中,應該忽略外部依賴具體的實現,而是通過模擬該接口方法來顯示的指定返回值,從而降低該返回值對於當前單元測試結果的影響,而 Mock 框架(例如最常用的Moq),剛好可以滿足我們對於接口的模擬需求。

參考文章 https://www.cnblogs.com/xboo/p/11811838.html

其他

using Auth.Application.IService;
using Auth.Application.Service;
using Auth.Model;
using Auth.Model.ViewModel;
using Auth.UI;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;

namespace UnitTest
{
    [TestClass]
    public class UnitTest1
    {
        private IUserService _controller;
        [TestMethod]
        public void TestMethod1()
        {

            var server = new TestServer(WebHost.CreateDefaultBuilder().UseStartup<Startup>());

            _controller = server.Host.Services.GetService<IUserService>();

            var ss = _controller.UserList(1,10).Result.Item1;






#if DEBUG
            //創建一個計時器,用來記錄程序的運行時間
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();//開始計時

            //var search1 = await _elasticsearch.QueryAsync(KeyWord, pageIndex, pageSize);

            sw.Stop();//結束計時
            var time = sw.Elapsed;
#endif

            Assert.IsTrue(true);
            //Assert.AreEqual(true,true);
        }
    }
}

參考

https://www.cnblogs.com/yubaolee/archive/2018/07/07/DotNetCoreUnitTest.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM