18

I want to unit test the following ASP.NET MVC controller Index action. What do I replace the actual parameter in the assert below (stubbed with ?).

using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
    public class StatusController : Controller
    {
        public ActionResult Index()
        {
            return Content("Hello World!");
        }
    }
}


[TestMethod]
public void TestMethod1()
{
    // Arrange
    var controller = CreateStatusController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.AreEqual( "Hello World!.", ? );
}
Robert MacLean
  • 38,975
  • 25
  • 98
  • 152
Nicholas Murray
  • 13,305
  • 14
  • 65
  • 84

3 Answers3

22

use the "as" operator to make a nullable cast. Then simply check for a null result

[TestMethod]
public void TestMethod1()
{
    // Arrange
    var controller = CreateStatusController();

    // Act
    var result = controller.Index() as ContentResult;

    // Assert
    Assert.NotNull(result);
    Assert.AreEqual( "Hello World!.", result.Content);
}
CVertex
  • 17,997
  • 28
  • 94
  • 124
11

I like creating assertion helpers for this sort of thing. For instance, you might do something like:

public static class AssertActionResult {
    public static void IsContentResult(ActionResult result, string contentToMatch) {
        var contentResult = result as ContentResult;
        Assert.NotNull(contentResult);
        Assert.AreEqual(contentToMatch, contentResult.Content);        
    }
}

You'd then call this like:

[TestMethod]
public void TestMethod1()
{
    var controller = CreateStatusController();
    var result = controller.Index();

    AssertActionResult.IsContentResult(result, "Hello World!");    
}

I think this makes the tests so much easier to read and write.

Seth Petry-Johnson
  • 11,845
  • 7
  • 49
  • 69
  • That's a great idea Seth. I have quite a few of the ContentResult unit tests to code so this will help on trying to keep to the DRY philosophy . – Nicholas Murray Feb 25 '10 at 20:21
  • @Nicholas: Glad you found it helpful. Other helpers I have are `AssertActionResult.IsRedirectTo(result, url)` and `AssertActionResult.IsViewResult(result, viewName)`. – Seth Petry-Johnson Feb 25 '10 at 20:25
4

You cant test that the result is not null, that you receive a ContentResult and compare the values:

[TestMethod]
public void TestMethod1()
{
    // Arrange
    var controller = CreateStatusController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.NotNull(result);
    Assert.IsAssignableFrom(typeof(ContentResult), result);
    Assert.AreEqual( "Hello World!.", result.Content);
}

I apoligize if the Nunit asserts aren't welformed, but look at it as pseudo-code :)

Alex Nolasco
  • 18,750
  • 9
  • 86
  • 81
Luhmann
  • 3,860
  • 26
  • 33