[英]Error in Unit Test MVC Controller using Fake
我正在嘗試對MoviesContrller進行單元測試。 控制器如下創建,
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);
}
}
}
為了對Index動作進行單元測試,我創建了如下的FakeRepository,
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>;
}
}
我編寫了有關索引操作的單元測試,如下所示,
[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);
}
如您在注釋中看到的,始終result.model返回null,而WasGetAllMoviesCalled get返回true。 我設置了一個斷點來調試測試。
Db.GetAllMovies()返回電影列表。 但令我驚訝的是,電影的價值始終為空。 我確定我在這里做一些愚蠢的事情。 請記住,db.GetAllMovies()正在調用FakeMovieRepository的GetAllMovies函數。 理想情況下,電影應包含從db.GetAllMovies()返回的電影列表。
有什么幫助嗎? 如何在不使用模擬的情況下對控制器進行單元測試。
List <T>不實現IQueryable <T>。
外觀http://msdn.microsoft.com/zh-cn/library/6sh2ey19(v=vs.110).aspx
您需要定義方法GetAllMovies的定義。 因此它將是repo.GetAllMethods =()=> {return new List <>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.