繁体   English   中英

单元测试LINQ返回整数

[英]Unit testing LINQ which returns an integer

我有这个测试,可以验证是否在我的引用中调用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()返回存储库中的全部,以计数哪些UserId为null。 即使仅验证linq的query()部分,也可以说测试还可以吗? 算什么?

如果要确保返回正确的计数,则需要安排模拟的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方法进行单元测试,那么我认为您可能需要重组生产代码,因为不需要单元测试框架方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM