# BookinHelper and BookingHelperTests:NullReferenceException :

**URL:** <https://forum.codewithmosh.com/t/bookinhelper-and-bookinghelpertests-nullreferenceexception/18510>\
**Category:** C#\
**Created:** [March 3, 2023, 4:49am UTC](https://forum.codewithmosh.com/t/bookinhelper-and-bookinghelpertests-nullreferenceexception/18510 "2023-03-03T04:49:11Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![whale442](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/whale442/32/4816_2.png) [@whale442](https://forum.codewithmosh.com/u/whale442)\
**Post date:** [March 3, 2023, 4:49am UTC](https://forum.codewithmosh.com/t/bookinhelper-and-bookinghelpertests-nullreferenceexception/18510/1 "2023-03-03T04:49:11Z")

</div>

Hi Teacher,  
I’ve been getting issues while running the BookingHelperTest.

Console output:  
System.NullReferenceException : Object reference not set to an instance of an object.

---

<div class="post-metadata">

**Author:** ![UniqueNospaceShort](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/uniquenospaceshort/32/1814_2.png) [@UniqueNospaceShort](https://forum.codewithmosh.com/u/UniqueNospaceShort)\
**Post date:** [March 4, 2023, 11:13am UTC](https://forum.codewithmosh.com/t/bookinhelper-and-bookinghelpertests-nullreferenceexception/18510/2 "2023-03-04T11:13:12Z")

</div>

Hi,

Welcome in here.  
As of your question, how anybody could help if you do not provide code?  
At most I could tell `NullReferenceException` happens most likely because you try using an object that wasn’t initialized yet.

Should you need more help please copy/paste your code here (preferred) or screenshots of relevant code.

Code should be surrounded by 3 backticks ( **`** ← Copy that character if you don’t know how to produce it) both before and after the code snippet.

> Example

![image](https://us1.discourse-cdn.com/flex020/uploads/codewithmosh/original/2X/b/b1bd6109b1ce96aebbc8773ba5f6d089bd689f68.png)

> Result

```auto
I am a code snippet.
Unlike classic markdown, 
    in this forum 
I shall not precise which language it is.

```

> Another Example

```auto
class Untitled-1
{   
    private int myVar;
    public int MyProperty
    {
        get { return myVar; }
        set { myVar = value; }
    }

    public Untitled-1(int parameter)
    {
        MyProperty=parameter;
    }

    private void MyMethod(int params){
        MyProperty += params;
    }    
}

```

Cheers.

---

<div class="post-metadata">

**Author:** ![whale442](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/whale442/32/4816_2.png) [@whale442](https://forum.codewithmosh.com/u/whale442)\
**Post date:** [March 4, 2023, 3:35pm UTC](https://forum.codewithmosh.com/t/bookinhelper-and-bookinghelpertests-nullreferenceexception/18510/3 "2023-03-04T15:35:46Z")

</div>

Thank you for your swift response.

 ![Screenshot 2023-03-04 at 16.28.52](https://us1.discourse-cdn.com/flex020/uploads/codewithmosh/original/2X/8/882b2e1c949c4fb44cb149c6b817cd9a3c65ddc3.jpeg)

 ![Screenshot 2023-03-04 at 16.32.09](https://us1.discourse-cdn.com/flex020/uploads/codewithmosh/original/2X/1/117f4657422cfae9b8e73d1471cb00c243f78403.jpeg)

---

<div class="post-metadata">

**Author:** ![whale442](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/whale442/32/4816_2.png) [@whale442](https://forum.codewithmosh.com/u/whale442)\
**Post date:** [March 4, 2023, 3:41pm UTC](https://forum.codewithmosh.com/t/bookinhelper-and-bookinghelpertests-nullreferenceexception/18510/4 "2023-03-04T15:41:21Z")

</div>

BookHelper.cs  
using System;  
using System.Collections.Generic;  
using System.Linq;

namespace TestNinja.Mocking  
{  
public static class BookingHelper  
{

```
    public static string OverlappingBookingsExist(Booking booking, IBookingRepository repository)
    {
        if (booking.Status == "Cancelled")
            return string.Empty;
            //return null;

        var bookings = repository.GetActiveBookings(booking.Id);
        var overlappingBooking =
            bookings.FirstOrDefault(
                b =>
        //booking.ArrivalDate < b.DepartureDate &&
        //b.ArrivalDate < booking.DepartureDate);
        booking.ArrivalDate >= b.ArrivalDate
        && booking.ArrivalDate < b.DepartureDate
        || booking.DepartureDate > b.ArrivalDate
        && booking.ArrivalDate <= b.DepartureDate);
        return overlappingBooking == null? string.Empty : overlappingBooking.Reference;
    } 
}

public interface IUnitOfWork
{
    IQueryable<T> Query<T>();
}

public class UnitOfWork : IUnitOfWork
{
    public IQueryable<T> Query<T>()
    {
        return new List<T>().AsQueryable();
    }
}

public class Booking
{
    public string Status { get; set; }
    public int Id { get; set; }
    public DateTime ArrivalDate { get; set; }
    public DateTime DepartureDate { get; set; }
    public string Reference { get; set; }
}

```

}

BookHelperRepository.cs

using System.Linq;

namespace TestNinja.Mocking  
{  
public interface IBookingRepository  
{  
IQueryable GetActiveBookings(int? excludedBookingId = null);  
}

```
public class BookingRepository : IBookingRepository
{
    public IQueryable<Booking> GetActiveBookings(int? excludedBookingId = null)
    {
        var unitOfWork = new UnitOfWork();
        var bookings =
            unitOfWork.Query<Booking>()
                .Where(
                    b => b.Status != "Cancelled");

        if (excludedBookingId.HasValue)
            bookings = bookings.Where(b => b.Id != excludedBookingId.Value);

        return bookings;
    }
}

```

}

BookHelperTest.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using Moq;  
using NUnit.Framework;  
using TestNinja.Mocking;

namespace TestNinja.UnitTests.Mocking  
{  
[TestFixture]  
public class BookingHelper\_OverlappingBookingsExistTests  
{  
private Booking \_booking;  
private Mock \_repository;  
private Booking \_existingBooking;

```
    [SetUp]
	public void SetUp()
	{
        _booking = new Booking
        {
            Id = 2,
            ArrivalDate = ArriveOn(2017, 1, 15),
            DepartureDate = DepartOn(2017, 1, 20),
            Reference = "a"
        };

        _repository = new Mock<IBookingRepository>();
        _repository.Setup(r => r.GetActiveBookings(1)).Returns(new List<Booking>
        {
            _booking

        }.AsQueryable());
    }

    [Test]
	public void BookingStartsAndFinishesBeforeAnExistingBooking_ReturnEmptyString()
	{
        var result = BookingHelper.OverlappingBookingsExist(new Booking 
        {
            Id = 1,
            ArrivalDate = Before(_existingBooking.ArrivalDate, days: 2),
            DepartureDate = Before(_existingBooking.ArrivalDate)
        }, _repository.Object);

        Assert.That(result, Is.Empty);
    }
    [Test]
    public void BookingStartsBeforeAndFinishesInTheMiddleOfAnExistingBooking_ReturnExistingBookingReference()
    {
        var result = BookingHelper.OverlappingBookingsExist( new Booking
        {
            Id = 1,
            ArrivalDate = Before(_existingBooking.ArrivalDate),
            DepartureDate = After(_existingBooking.ArrivalDate)
        }, _repository.Object);

        Assert.That(result, Is.EqualTo(_existingBooking.Reference));
    }
    [Test]
    public void BookingStartsBeforeAndFinishesAfterAnExistingBooking_ReturnExistingBookingReference()
    {
        var result = BookingHelper.OverlappingBookingsExist(new Booking
        {
            Id = 1,
            ArrivalDate = Before(_existingBooking.ArrivalDate),
            DepartureDate = After(_existingBooking.DepartureDate)
        }, _repository.Object);

        Assert.That(result, Is.EqualTo(_existingBooking.Reference));
    }

    [Test]
    public void BookingStartsAndExistingBookingButFinishesAfter_ReturnEmptyString()
    {
        var result = BookingHelper.OverlappingBookingsExist(new Booking
        {
            Id = 1,
            ArrivalDate = After(_existingBooking.ArrivalDate),
            DepartureDate = After(_existingBooking.DepartureDate, days: 2)
        }, _repository.Object);

        Assert.That(result, Is.Empty);
    }

    [Test]
    public void BookingsOverlapNewBookingIsCancelled_ReturnEmptyString()
    {
        var result = BookingHelper.OverlappingBookingsExist(new Booking
        {
            Id = 1,
            ArrivalDate = Before(_existingBooking.ArrivalDate),
            DepartureDate = After(_existingBooking.DepartureDate),
            Status = "Cancelled"
        }, _repository.Object) ;

        Assert.That(result, Is.Empty);
    }

    private DateTime Before(DateTime dateTime, int days = 1)
    {
        return dateTime.AddDays(-days);
    }  

    private DateTime After(DateTime dateTime, int days = 1)
    {
        return dateTime.AddDays(-days);
    }

    private DateTime ArriveOn(int year, int month, int day)
	{
		return new DateTime(year, month, day, 14, 0, 0);
	}
    private DateTime DepartOn(int year, int month, int day)
    {
        return new DateTime(year, month, day, 10, 0, 0);
    }
}

```

}
