MoqFrameworkFunc我是Moq和TDD的新手,我想做的是在存储库接口上设置一个方法。这是全文。我有一个名为Tenant的域实体类,其属性为BusinessIdentificationNumberpublicclassTenant:EntityBase,IAggregateRoot{...publicstringBusinessIdentificationNumber{get;放;}...}接下来我有这个实体的存储库,接口LikepublicinterfaceIRepository{...TFindBy(Funcfunc);...}问题所在,我使用域名服务,其中包含创建租户的规则,例如publicclassTenantCreationService:ITenantCreationService{publicTenantCreationService(IRepositorytenantRepository){...}publicvoidCreateTenant(Tenanttenant){//从这里开始调用IRepository.FindBy(funcMethod);在我测试TenantCreationService的单元测试中,我模拟了传递给构造函数存储库的存储,但我想测试该功能:所以我尝试这样做repositoryMock.Setup(x=>x.FindBy(It.Is(t=>t.BusinessIdentificationNumber==_tenantInTest.BusinessIdentificationNumber))).Returns(_tenantInTest)但它没有编译。你知道我想做什么编辑:当我尝试编译以下代码片段时我得到异常Unsupportedexpression:t=>(t.BusinessNumber==value(DP.IPagac.UnitTests.DP.IPagac.Module.TenantManagement.TenantDomainServiceTests)._validTenant.BusinessNumber)我想你正在尝试的是这个(删除一些不相关的东西,比如创建ITenent,所以它可以动态模拟):[TestFixture]publicclassTest{[Test]publicvoidCreateTenentAlreadyExistsTest(){vartenentMock=newMock();varrepoMock=newMock>();tenentMock.Setup(t=>t.BusinessIdentificationNumber).Returns("aNumber");repoMock.Setup(r=>r.FindBy(It.Is>(func1=>func1.Invoke(tenentMock.Object)))).Returns(tenentMock.Object);vartenantCreationService=newTenantCreationService(repoMock.Object);tenantCreationService.CreateTenant(tenentMock.Object);tenantMock.VerifyAll();repoMock.VerifyAll();}}publicinterfaceITenant{stringBusinessIdentificationNumber{get;放;}}publicclassTenant:ITenant{publicstringBusinessIdentificationNumber{get;放;}}publicinterfaceIRepository{TFindBy(System.Funcfunc);}publicclassTenantCreationService:ITenantCreationService{privatereadonlyIRepository_tenantRepository;ServiceTIRenantCreation(_tenantRepository=tenantRepository;}publicvoidCreateTenant(ITenanttenant){varexistingTenant=_tenantRepository.FindBy(t=>t.BusinessIdentificationNumber==tenant.BusinessIdentificationNumber);if(existingTenant==null){//dostuff}}}publicinterfaceITenantCreationService{voidCreateTenant(ITenanttenant);}“当具有BusinessIdentificationNumber的租户已经存在于商店或会话中时,应该返回它”-来自这个测试描述我明白你应该在存储库类而不是服务中测试这种行为在服务的单元测试中,你不应该测试数据访问层我的意思是你的存储库,你应该只验证存储库方法FindBy被调用。我建议创建从IRepository接口和基类Repostiry派生的ITenantRepositry。以上就是C#学习教程:Moq框架Func分享的全部内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
