使用单元测试、工作单元和通用存储库模式框架从最小起订量获取单个对象

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** 

    ...
}

有两件事需要解决:

模拟 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(值无关紧要)和 returns 一个 WebStore 对象的集合.

将对返回的模拟值调用 FirstOrDefault

根据@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);