【发布时间】:2014-09-04 02:23:36
【问题描述】:
我正在尝试测试使用以下域对象的方法。
public class PartyRoom
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Capacity { get; set; }
public bool IsAvailable { get; set; }
public virtual ICollection<RoomBooking> Bookings { get; set; }
}
public class RoomBooking
{
public int Id { get; set; }
public BookingType BookingType { get; set; }
public int PartyRoomId { get; set; }
public int TimeSlotId { get; set; }
public DateTime Date { get; set; }
public virtual PartyRoom PartyRoom { get; set; }
public virtual TimeSlot TimeSlot { get; set; }
}
public enum BookingType
{
PartyOrder,
RoomRental,
Corporate
}
我有一个存储库模拟,我正在为这样的房间预订设置:
_roomBookingRepositoryMock.Setup(x => x.Get()).Returns(roomBookings.AsQueryable);
返回的roomBookings 如下所示:
var roomBookings = new List<RoomBooking>
{
new RoomBooking()
{
Id = 1,
BookingType = BookingType.PartyOrder,
Date = new DateTime(2014, 11, 15),
PartyRoomId = 2,
TimeSlotId = 1
},
new RoomBooking()
{
Id = 2,
BookingType = BookingType.PartyOrder,
Date = new DateTime(2014, 11, 15),
PartyRoomId = 4,
TimeSlotId = 3
},
new RoomBooking()
{
Id = 3,
BookingType = BookingType.PartyOrder,
Date = new DateTime(2014, 11, 15),
PartyRoomId = 5,
TimeSlotId = 4
}
};
当我运行测试时,public virtual ICollection<RoomBooking> Bookings { get; set; } 始终为空。我不确定如何设置该属性,因为我的房间预订列表没有被模拟,所以SetupGet 似乎不起作用?
当我运行测试时,我得到:
System.ArgumentNullException : 值不能为空。
单步执行时显示属性为空。我想我不能假设 NUnit 会像 Entity Framework 首先在代码中那样连接它,但我很难理解如何访问它并设置属性。
*我尽可能多地发布了代码,由于项目原因我无法共享方法本身,但我可以确认问题是属性为空且未设置。
【问题讨论】:
-
'当我运行测试时发生了什么......' 你能把你的测试也发布吗?
-
您所说的
Bookings属性似乎是PartyRoom类的一部分,但您从未在代码中使用它。此外,当您创建PartyRoom的实例时,如果您从不更改它,请确保Bookings是null。你期望发生什么?抱歉,我不清楚。 -
Bookings 作为虚拟属性链接到 roomBookingsRepository,并且在正常运行时拉入链接到派对房间 ID 的预订。这是EF中的一对多关系。我想我可能需要模拟我的 DBSet 来测试它。
标签: c# unit-testing mocking nunit moq