且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Moq框架Func< T,T>

更新时间:2022-03-13 15:02:17

我认为您要达到的目的是这样的(删除了一些无关紧要的东西,并创建了ITenent,以便可以对其进行动态模拟):

I think what you are trying the acheive is this (removed some things that were extraneous for example and created ITenent so it can be mocked dynamically):

[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);
}