Iam为我的存储库编写单元测试,我需要使用委托测试存储库方法。
首先来自存储库界面
public interface IRepository<T>
{
...
IQueryable<T> All();
...
}
这是我要测试的方法。我将其作为IRepository<RentDetails>
public static bool AnyIntersectionForRoomWithDatesExists
(this IRepository<RentDetails> repository, Room room, DateTime startDate,
DateTime terminationDate)
{
var rent = repository.All().Where(
r =>
(r.BeginningDate <= startDate && r.TerminationDate > terminationDate &&
r.TerminationDate < terminationDate) ||
(r.BeginningDate > startDate) ||
(r.TerminationDate >= terminationDate && r.BeginningDate > startDate &&
r.BeginningDate < terminationDate));
}
在我的单元测试中,我创建了一个IEnumerable<RentDetails>
集合
IEnumerable<RentDetails> rentDetailsColection = new List<RentDetails>
{
new RentDetails(TenantTestHelper.ValidTenant,roomMoq, new DateTime(2012, 1, 1),new DateTime(2012, 2, 1)),
new RentDetails(TenantTestHelper.ValidTenant,roomMoq, new DateTime(2012, 3, 1),new DateTime(2012, 7, 1)),
new RentDetails(TenantTestHelper.ValidTenant,roomMoq, new DateTime(2012, 10, 1),DateTime.MaxValue)
};
但我有一个问题如何设置存储库moq?我尝试了以下
[Test]
var reqestStartDate = new DateTime(2012, 4, 1);
var requestTerminationDate = reqestStartDate.AddDays(30);
...
rentDetailsRepositoryMoq.Setup(c => c.All().Where(r =>
(r.BeginningDate <= reqestStartDate &&
r.TerminationDate > requestTerminationDate &&
r.TerminationDate < requestTerminationDate) ||
(r.BeginningDate > reqestStartDate) ||
(r.TerminationDate >= requestTerminationDate &&
r.BeginningDate > reqestStartDate &&
r.BeginningDate < requestTerminationDate)))
.Returns((IQueryable<RentDetails>)rentDetailsColection
.Where(r =>(r.BeginningDate <= reqestStartDate &&
r.TerminationDate > requestTerminationDate &&
r.TerminationDate < requestTerminationDate) ||
(r.BeginningDate > reqestStartDate) ||
(r.TerminationDate >= requestTerminationDate &&
r.BeginningDate > reqestStartDate && r.BeginningDate < requestTerminationDate)));
但我有例外
NotSupportedException
表达式引用不属于模拟对象的方法:c =&gt; c.All()。其中(r =&gt;(((r.BeginningDate&lt; = .reqestStartDate&amp;&amp; r.TerminationDate&gt; .requestTerminationDate)&amp;&amp; r.TerminationDate&lt; .requestTerminationDate)|| r .BeginningDate&gt; .reqestStartDate)||((r.TerminationDate&gt; = .requestTerminationDate&amp;&amp; r.BeginningDate&gt; .reqestStartDate)&amp;&amp; r.BeginningDate&lt; .requestTerminationDate))
答案 0 :(得分:4)
只需Setup
IRepository.All()
即可返回IQueryable<T>
并断言被测单元正在执行应该执行的操作。请注意,通过传统定义,您正在尝试对存储库进行存根,并且您将断言状态。