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() 部分,是否可以说测试是可以的?计数呢?

4

1 回答 1

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 方法进行单元测试,那么我认为您可能想要重组您的生产代码,因为单元测试框架方法是不必要的。

于 2016-05-03T20:35:49.453 回答