Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test on MVC 3 Controller returns null for results, but I can see them in Immediate Window

I am new to MVC and Unit Test. I am using Visual Studio unit test framework to test a product controller. The controller works on actual website but it always returns null in Unit Test. I have switch around keyword such as ViewResult or name of Model but all of them doesn't work because controller always return null. Then I put breaking point and start debug the testing code. When I test it in Immediate Window it has value.

What am I missing here?

I have a screenshot on this URL: http://i.imgur.com/XBmoh.png In screenshot you can see the Immediate Window the model is passed from controller successful, P4 P5 is stored in result. It just not work in UnitTest.

The List code is quite simple, It works fine on website. here is the code

    public int PageSize = 4;
    private IProductRepository repository;

    public ProductController(IProductRepository productRepository)
    {
        repository = productRepository;
    }

    public ViewResult List(int page=1)
    {
        ProductsListViewModel viewModel = new ProductsListViewModel
        {
            Products = repository.Products
            .OrderBy(p => p.ProductID)
            .Skip((page - 1) * PageSize)
            .Take(PageSize).AsEnumerable(),
            PagingInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = repository.Products.Count()
            }
        };

        return View(viewModel);
    }
like image 272
SnowFox108 Avatar asked Nov 26 '12 19:11

SnowFox108


1 Answers

Had this problem before, you are not using the same versions of System.Web.Mvc in your projects. You must reference the same version of System.Web.Mvc both in your main project and unit test project.

like image 110
Saber Avatar answered Oct 03 '22 21:10

Saber