Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing repository with Moq

I'm utterly new to Moq and so far have just follwed the examples outlined in Pro asp.net framework. In the book, some of the crud is placed in the controller, such as getting customer by id - possibly for reasons of brevity. I've decided to place that type of functionality in the repository and just call it in the controller like so "customerRepository.GetCustomerByID(id);" What's the best way to test something like this?I've created the following unit test, which for some reason returns a null Customer.

List<Customer> customer = new List<Customer>();

customer.Add(new Customer { CustomerId = 1, FirstName = "test", LastName = "wods", Sex = true });
mockRepos = new Moq.Mock<ICustomerRepository>();
mockRepos.Setup(x => x.Customers).Returns(customer.AsQueryable());

CustomersController controller = new CustomersController(mockRepos.Object);

//Act
ViewResult results = controller.Edit(1);

var custRendered = (Customer)results.ViewData.Model;
Assert.AreEqual(2, custRendered.CustomerId);
Assert.AreEqual("test", custRendered.FirstName);

And the controller

public ViewResult Edit(int id)
{
    Customer customer = customerRepository.GetCustomerByID(id);           

    return View(customer); //this just returns null??
}

I imagine I'm being very silly, but any help would be uber appreciated.

like image 229
hoakey Avatar asked Nov 29 '10 15:11

hoakey


1 Answers

you need to set your mock up to expect a call to GetCustomerById rather than the Customers property. Something like this:

mockRepos.Setup(x => x.GetCustomerById(1)).Returns(customer[0]);
like image 175
Mark Heath Avatar answered Oct 08 '22 06:10

Mark Heath