簡體   English   中英

使用單元測試、工作單元和通用存儲庫模式框架從 MOQ 中獲取單個對象

[英]Get single object from MOQ using Unit Testing, Unit of Work and Generic Repository Pattern framework

我是 Moq 的新手,目前,問題是當我嘗試獲取對象的集合(例如 WebStore)時,它按預期工作,但是當我嘗試從中獲取單個對象時,卻沒有按預期工作,

你能指導我如何從存儲庫中獲取單個對象嗎

private Mock<WebStore> _webstore; 
[SetUp]
public void SetUp()
{
  ...
               
    _unitOfWork = new Mock<IUnitOfWork>();           
    _webstore = new Mock<WebStore>();
    ...
}    

方法

public WebStore GetAllWebstore()
{            
   var webstoreDat = unitOfWork.GetRepository<WebStore>().GetAll();
   return webstoreData;
}

public WebStore GetWebstorebyId(int webstoreId)
{            
     var webstoreData = unitOfWork.GetRepository<WebStore>()
          .Get(store => store.WebStoreId == webstoreId).FirstOrDefault();
     return webstoreData;
}

測試方法

[Test]
public void GetWebstore_All()
{
    //
    var webStoreId = 1;
    var customerName = "A";
    var listWebstore = new List<WebStore>() { new WebStore { WebStoreId = webStoreId, CustomerName = customerName } };
    var webstore = new WebStore { WebStoreId = webStoreId, CustomerName = customerName };
   
   //Set up Mock        
    _unitOfWork.Setup(uow => uow.GetRepository<WebStore>().GetAll()).Returns(listWebstore); // working

    ...
}
[Test]
public void GetWebstore_GetSingle()
{
    //
    var webStoreId = 1;
    var customerName = "A";
    var listWebstore = new List<WebStore>() { new WebStore { WebStoreId = webStoreId, CustomerName = customerName } };
    var webstore = new WebStore { WebStoreId = webStoreId, CustomerName = customerName };
   
   //Set up Mock
    _unitOfWork.Setup(uow => uow.GetRepository<WebStore>()
    .Get(store => store.WebStoreId == webStoreId, null, "", 0, 0).FirstOrDefault()).Returns(webstore);  **//Not working** 

    ...
}

基於@PeterCsala 的幫助,它通過使用It.IsAny可以按預期工作:

_unitOfWork.Setup(x => x.GetRepository<WebStore>()
                .Get(It.IsAny<Expression<Func<WebStore, bool>>>(), It.IsAny<Func<IQueryable<WebStore>,
                IOrderedQueryable<WebStore>>>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(listWebstore);

有兩件事需要修復:

模擬Get方法

如果您像這樣重寫GetWebstorebyId方法:

var webstoreData = unitOfWork.GetRepository<WebStore>()
          .Get(store => store.WebStoreId == webstoreId);
return webstoreData.FirstOrDefault();

那么很明顯你應該模擬Get而不是Get + FirstOrDefault

在安裝過程中使用It.IsAny

因為您的模擬不依賴傳入參數,這就是為什么您不需要在設置期間將其指定為具體值的原因。

_unitOfWork
    .Setup(uow => uow.GetRepository<WebStore>().Get(It.IsAny<int>()))
    .Returns(listWebstore);

有了這個,您已經設置了Get方法,它將接收一個int (值無關緊要)並返回WebStore對象的集合。

FirstOrDefault將在返回的模擬值上調用。

暫無
暫無

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

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