Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test an ActionResult that returns a ContentResult?

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!.", ? );
}
like image 864
Nicholas Murray Avatar asked Feb 25 '10 16:02

Nicholas Murray


3 Answers

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);
}
like image 172
CVertex Avatar answered Nov 15 '22 05:11

CVertex


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.

like image 38
Seth Petry-Johnson Avatar answered Nov 15 '22 05:11

Seth Petry-Johnson


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 :)

like image 38
Luhmann Avatar answered Nov 15 '22 04:11

Luhmann