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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With