![](/img/trans.png)
[英]Create an iQueryable which is case insensitive for unit testing linq to entities - NSubstitute
[英]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.