Domanda

I have a controller method - CurrentValues

[HttpGet]
public ActionResult CurrentValues(ValueRetrieverViewModel valueRetrieverModel)
{
    int page = 0;
    if(!string.IsNullOrEmpty(valueRetrieverModel.Page))
    {
        int.TryParse(valueRetrieverModel.Page, out page);
    }

    if (page <= 0) page = 1;

    var values = GetValues(page);

    if (values != null)
    {
        if (values.QueryResults.Count > 0)
        {
            ViewData["name"] = valueRetrieverModel.Name; 
            ViewData["school"] = valueRetrieverModel.School;             
            ViewData["team"] = valueRetrieverModel.Team;
        }
    }

    var valRtrvrViewModel = new ValuesViewModel
    {
        Results = values,  
        InputParms = valueRetrieverModel
    };

    return View("CurrentValues", searchViewModel);
}

I would like to have this controller comprehensively unit tested by utilizing MS-VS-Unit Test Suite and if needed Moq too.

The core of this method is the retrieved values from - GetValues(page).

  1. What are the tests that I can write to have comprehensive unit testing for this method? Sample code would be helpful along with the test scenarios.
  2. How to use Moq to mock the ValueRetrieverViewModel? Should I or Can I use Moq for any other purpose here specifically?
È stato utile?

Soluzione

The following article is excellent in explaining in detail all the tests that you should write when testing controllers, including when to use a mocking framework. It is also short too. http://www.arrangeactassert.com/how-to-unit-test-asp-net-mvc-controllers/

Excerpt from the article:

Let me start off by discussing what types of unit tests you should be creating for MVC controllers. Tests to check the correct action result is returned from a controller action. This includes information about the action result, such as the testing the correct view is returned for a view result.

Tests to check if the view model is what you expected. If you have a strongly typed view which expects class foo and you pass class bar to your view model, your code will compile, would result in a runtime error like the one shown below.

If you are testing anything more than this your controller is doing too much.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top