I am trying to do Unit Testing of MoviesContrller. Controller is created as below,
public class MoviesController : Controller
{
private readonly IMovieRepository db;
public MoviesController(IMovieRepository db)
{
this.db = db;
}
public ActionResult Index(string movieGenre, string searchString, string BinderList)
{
var movies = db.GetAllMovies();
return View(movies);
}
}
}
To do unit testing of Index action, I have created FakeRepository as below,
public class FakeMovieRepository : IMovieRepository
{
public bool WasGetAllMoviesCalled { private set; get; }
public IQueryable<Movie> GetAllMovies()
{
WasGetAllMoviesCalled = true;
List<Movie> lstMovies = new List<Movie>
{
new Movie
{
Rating = "PG",
ID = 1,
Title = "When Harry Met Sally",
Price = 7.99M,
Genre = "Romantic Comedy",
ReleaseDate = Convert.ToDateTime("1/11/1989 12:00:00 AM")
}
};
return lstMovies as IQueryable<Movie>;
}
}
I have written Unit Test on Index action as below,
[TestMethod]
public void ReturnAllMoviesGivenEmptyStringParameters()
{
//Arange
FakeMovieRepository repo = new FakeMovieRepository();
var moviesController = new MoviesController(repo);
//Actual
var result = moviesController.Index(String.Empty, String.Empty,String.Empty ) as ViewResult;
// returning null always :( on debigging found that calling fake repo function but returning null !
var movies = result.Model as IQueryable<Movie>;
// Assert
Assert.AreEqual(true, repo.WasGetAllMoviesCalled);
}
As you see in the comment that always result.model returns null whereas WasGetAllMoviesCalled get returns as true. I put a breakpoint to debug test.
Db.GetAllMovies() returns List of Movie. But to my surprise values of movies is always null. I am sure I am doing something stupid here. Keep in mind that db.GetAllMovies() is calling GetAllMovies function of FakeMovieRepository. Ideally movies should contain List of movies returned from db.GetAllMovies()
Any help on same? How to unit test controller without using mock.
List< T > doesn't implement IQueryable< T >.
Look http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments