使用假的单元测试MVC控制器出错

时间:2014-09-03 08:38:26

标签: asp.net-mvc unit-testing controller

我正在尝试对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返回为true。我给断点调试了一下。

BreakPoint on Index

Db.GetAllMovies()返回电影列表。但令我惊讶的是,电影的价值总是空的。我相信我在做一些愚蠢的事情。请记住,db.GetAllMovies()正在调用FakeMovieRepository的GetAllMovies函数。理想情况下,电影应包含从db.GetAllMovies()

返回的电影列表

有任何帮助吗?如何在不使用mock的情况下对控制器进

2 个答案:

答案 0 :(得分:2)

列表与LT; T>没有实现IQueryable&lt; T&gt;。

http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

答案 1 :(得分:0)

您需要定义方法GetAllMovies的定义。所以它将是repo.GetAllMethods =()=&gt; {return new List&lt;&gt;();