单元测试LINQ,返回一个整数

时间:2016-05-02 09:49:50

标签: c# unit-testing mocking nunit nunit-3.0

我有这个测试,它验证我是否在我的参考中调用了Query()。

[TestFixture]
public class When_retrieving_an_application_license
{
    [Test]
    public void available_licenses_should_be_counted()
    {
        // Arrange
        var sut = new LicenseManager();
        var mockILicenseRepository = new Mock<ILicenseRepository>();
        sut.LicenseRepository = mockILicenseRepository.Object;
        // Act
        sut.GetLicenseCount(Guid.NewGuid(), Guid.NewGuid());
        // Assert
        mockIApplicationLicenseRepository.Verify(x => x.Query());
    }
}

但是,GetLicenseCount(Guid.NewGuid(),Guid.NewGuid())函数如下所示:

 public int GetLicenseCount(Guid cId, Guid appId) 
          => LicenseRepository.Query()
             .Count(al => al.CId == cId && al.AppId == appId 
                                        && al.UserId == null 
                                        && al.Expiry > DateTime.UtcNow);

Query()返回repo中的all以计算哪些UserId为null。 即使它只验证了linq的query()部分,它是否足以说测试没问题? 伯爵怎么样?

1 个答案:

答案 0 :(得分:0)

如果您想确保返回正确的计数,则需要安排模拟的ILicenseRepository以返回您期望的数据。

var mockILicenseRepository = new Mock<ILicenseRepository>();
mockILicenseRepository.Setup(x => x.Query()).Returns(new {CId = guid, AppId = guid2, Expiry = DateTime.Now.AddDays(1)};

您还需要将返回值存储为断言

var actualCount = sut.GetLicenseCount(Guid.NewGuid(), Guid.NewGuid());
Assert.AreEqual(expectedCount, actualCount);

但是,如果您正在对LINQ的Query方法进行单元测试,那么我认为您可能需要重新构建生产代码,因为不需要单元测试框架方法。