I'm trying to run some unit tests and I need to do the [TestInitialize]
thing.
I found some info in this post. I have no idea how to fix it because it makes no sense to me.
[TestInitialize]
public void TestInitialize()
{
mock = new Mock<ILibraryRepository>();
books = new List<Book>()
{
new Book { Id = 0, Title = "Title 0", Edition = 0, PublicationDate = DateTime.Now, Author = { Id = 0, Name = "Author 0", DateOfBirth = DateTime.Now, DateOfDeath = DateTime.Now }, AuthorId = 0 },
new Book { Id = 1, Title = "Title 1", Edition = 1, PublicationDate = DateTime.Now, Author = { Id = 1, Name = "Author 1", DateOfBirth = DateTime.Now, DateOfDeath = DateTime.Now }, AuthorId = 1 },
new Book { Id = 2, Title = "Title 2", Edition = 2, PublicationDate = DateTime.Now, Author = { Id = 2, Name = "Author 2", DateOfBirth = DateTime.Now, DateOfDeath = DateTime.Now }, AuthorId = 2 }
};
mock.Setup(m => m.Books).Returns(books.AsQueryable());
var controller = new BooksController(mock.Object);
}
It looks all good and fine. But when I run this test:
[TestMethod]
public void IndexLoadsValid()
{
// Arrange
var controller = new BooksController(mock.Object);
// Act
var result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
I get the following error:
object reference not set to an instance of an object
And this is clear. It's null. But what I don't understand is why it's null?
The debugging says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Assignment2.Models.Book.Author.get returned null.
And this makes no sense to me because this function works when I fire up the program.
The Book
model is here:
public class Book
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Display(Name = "Publication date")]
public DateTime? PublicationDate { get; set; }
public float? Edition { get; set; } // We might have a 2.5 edition. Rare but happens
public int AuthorId { get; set; }
public Author Author { get; set; }
}
I have no idea if it helps but my ILibraryRepository
is here:
public interface ILibraryRepository
{
IQueryable<Book> Books { get; }
IQueryable<Author> Authors { get; }
Book Save(Book book);
Author Save(Author author);
void Delete(Book book);
void Delete(Author author);
}
Any idea why I'm getting this error?
EDIT: I changed the HomeController
to BooksController
. I have no idea why I mixed the two here. The error is happening in the [TestInitialize]
part