我是 Moq 和 TDD 的新手,我想做的是在存储库接口(interface)上设置方法。
这里是完整的故事。
我有一个名为 Tenant 的域实体类,其属性为 BusinessIdentificationNumber
public class Tenant:EntityBase<Tenant>,IAggregateRoot
{
...
public string BusinessIdentificationNumber {get;set;}
...
}
接下来我有这个实体的存储库,它的界面是这样的
public interface IRepository<T>
{
...
T FindBy(Func<T,bool> func);
...
}
问题出在哪里,我使用了一个域服务,它包含创建租户的规则,就像
public class TenantCreationService:ITenantCreationService
{
public TenantCreationService(IRepository<Tenant> tenantRepository){...}
public void CreateTenant(Tenant tenant)
{
//from here there is call to IRepository<Tenant>.FindBy(funcMethod);
}
}
在我测试 TenantCreationService 的单元测试中,我模拟了传递给构造函数的存储库,但我想测试该功能:
- 当具有 BusinessIdentificationNumber 的租户已存在于存储或 session 中时,应将其返回。
所以我试着这样做
repositoryMock.Setup(x=>x.FindBy(It.Is<Tenant>(t=>t.BusinessIdentificationNumber
== _tenantInTest.BusinessIdentificationNumber))).Returns(_tenantInTest)
但它不编译。你知道我想做什么吗?
编辑: 当我尝试编译下面的代码片段时
repositoryMock.Setup(e => e.FindBy(t => t.BusinessNumber == _validTenant.BusinessNumber)).Returns(
_validTenant);
我得到异常
Unsupported expression: t => (t.BusinessNumber == value(DP.IPagac.UnitTests.DP.IPagac.Module.TenantManagement.TenantDomainServiceTests)._validTenant.BusinessNumber)
最佳答案
我认为你正在尝试实现的是这个(例如删除了一些无关的东西并创建了 ITenent 以便它可以被动态模拟):
[TestFixture]
public class Test
{
[Test]
public void CreateTenentAlreadyExistsTest()
{
var tenentMock = new Mock<ITenant>();
var repoMock = new Mock<IRepository<ITenant>>();
tenentMock.Setup(t => t.BusinessIdentificationNumber).Returns("aNumber");
repoMock.Setup(r => r.FindBy(It.Is<System.Func<ITenant, bool>>(func1 => func1.Invoke(tenentMock.Object)))).Returns(tenentMock.Object);
var tenantCreationService = new TenantCreationService(repoMock.Object);
tenantCreationService.CreateTenant(tenentMock.Object);
tenentMock.VerifyAll();
repoMock.VerifyAll();
}
}
public interface ITenant
{
string BusinessIdentificationNumber { get; set; }
}
public class Tenant : ITenant
{
public string BusinessIdentificationNumber { get; set; }
}
public interface IRepository<T>
{
T FindBy(System.Func<T, bool> func);
}
public class TenantCreationService : ITenantCreationService
{
private readonly IRepository<ITenant> _tenantRepository;
public TenantCreationService(IRepository<ITenant> tenantRepository)
{
_tenantRepository = tenantRepository;
}
public void CreateTenant(ITenant tenant)
{
var existingTenant =
_tenantRepository.FindBy(t => t.BusinessIdentificationNumber == tenant.BusinessIdentificationNumber);
if (existingTenant == null)
{
//do stuff
}
}
}
public interface ITenantCreationService
{
void CreateTenant(ITenant tenant);
}
关于c# - Moq 框架 Func<T,T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228164/