Я реализую модульный тест для проверки метода в классе помощника.
Я смоделировал свой интерфейс IRepository и передал его объект в смоделированный IUnitOfWork, потому что этот интерфейс IRepository является свойством для UnitOfWork. При отладке модульного теста я обнаружил, что вызов _unitOfWork.Booking.OverlappingBooking в классе помощника всегда возвращает нуль. OverlappingBooking () вообще не вызывается.
public class BookingHelper
{
private IUnitOfWork _unitOfWork;
public BookingHelper(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public string OverlappingBookingsExist(Booking booking)
{
if (booking.Status == "Cancelled")
return string.Empty;
var bookings = _unitOfWork.Booking.GetActiveBookings<Booking>().Where(
b => b.Id != booking.Id && b.Status != "Cancelled");
var overlappingBooking = _unitOfWork.Booking.OverlappingBooking(bookings, booking);
return overlappingBooking;
}
}
my UnitOfWork
public interface IUnitOfWork
{
IBookingHelperRepository Booking { get; set; }
}
public class UnitOfWork: IUnitOfWork
{
public IBookingHelperRepository Booking { get; set; }
public UnitOfWork()
{
Booking = new BookingHelperRepository();
}
}
Репозиторий
public interface IBookingHelperRepository
{
IQueryable<T> GetActiveBookings<T>();
string OverlappingBooking(IQueryable<Booking> bookings, Booking booking);
}
public class BookingHelperRepository: IBookingHelperRepository
{
public IQueryable<T> GetActiveBookings<T>()
{
var resp = new List<T>().AsQueryable();
return resp;
}
public string OverlappingBooking(IQueryable<Booking> bookings, Booking booking)
{
var overlappingBooking = bookings.FirstOrDefault(
b => booking.ArrivalDate >= b.ArrivalDate
&& booking.ArrivalDate < b.DepartureDate
|| booking.DepartureDate > b.ArrivalDate
&& booking.DepartureDate <= b.DepartureDate);
return overlappingBooking == null ? string.Empty : overlappingBooking.Reference;
}
}
Я настроил свой тестовый класс, как показано ниже.
[TestClass]
public class BookingHelperTests
{
private Mock<IBookingHelperRepository> bookingHelperRepository;
private BookingHelper bookingHelper;
private Booking booking;
private Mock<IUnitOfWork> unitOfWork;
[TestInitialize]
public void Initialise()
{
unitOfWork = new Mock<IUnitOfWork>();
bookingHelper = new BookingHelper(unitOfWork.Object);
bookingHelperRepository = new Mock<IBookingHelperRepository>();
.....
}
[TestMethod]
public void OverlappingBookingsExist_BookingStartsAndFinishesBeforeAnExistingBooking_ShouldReturnEmptyString()
{
bookingHelperRepository.Setup(y => y.GetActiveBookings<Booking>()).Returns(bookingListBefore.AsQueryable());
unitOfWork.Setup(x => x.Booking).Returns(bookingHelperRepository.Object);
//Act
var result = bookingHelper.OverlappingBookingsExist(booking);
//Assert
Assert.AreEqual("", result);
}