开发者

How to get result from ControllerContext

My controller action returns a custom ActionResult that executes either a success or failure result depending on some validation logic. This happens within ExecuteResult.

My question is, how can I check the result?

Here's the test so far:

[TestFixture]
public class FormActionResultTests
{
    TestController controller;

    [SetUp]
    public void SetUp()
    {
        ObjectFactory.Initialize(cfg =>
        {
            cfg.For<IFormHandler<TestModel>>().Use<TestModelHandler>();
        });

        controller = new TestControllerBuilder().CreateController<TestController>();
    }

    [Test]
    public void Valid_input_returns_success_result()
    {
        var result = controller.Test(new TestModel { IsValid = true, IsValid2 = true })
            .AssertResultIs<FormActionResult<TestModel>>();

        var context = controller.ControllerContext;

        result.ExecuteResult(context); 
        // how to verify result?

    }
}

public class TestController : Controller
{
    public ActionResult Test(TestModel model) {
        return new FormActionResult<TestModel>(model, this.Content("Success"), View(model));
    }
}

public class TestModel {
    public开发者_如何学Python bool IsValid { get; set; }
    public bool IsValid2 { get; set; }
}

public class TestModelHandler : IFormHandler<TestModel>
{
    public void Handle(TestModel form, IValidationDictionary validationDictionary)
    {

    }
}

Update

Here's what worked for me in the end (using NSubstitute):

    [Test]
    public void Valid_input_returns_success_result()
    {
        var result = new FormActionResult<TestModel>(new TestModel { IsValid = true, IsValid2 = true },
            new ContentResult { Content = "Success" }, new ContentResult { Content = "Failed" });

        var sb = new StringBuilder();
        var response = Substitute.For<HttpResponseBase>();
        response.When(x => x.Write(Arg.Any<string>())).Do(ctx => sb.Append(ctx.Arg<string>()));
        var httpContext = Substitute.For<HttpContextBase>();
        httpContext.Response.Returns(response);

        var controllerContext = new ControllerContext(httpContext, new RouteData(), new TestController());

        result.ExecuteResult(controllerContext);

        sb.ToString().ShouldEqual("Success");
    }


Controller should be tested that they return correct ActionResult in your case, and the Success or Failure of ActionResult should be tested by ActionResultTest and it has nothing to do with controller. Unit test means single unit test - but you test both controller and ActionResult in the same test, that is incorrect. To test ActionResult, first imagine that generally all that ActionResult does, is writing result to HttpResponse. Let's rewrite your code to use Moq to supply StringWriter for ControllerContext.HttpContext.HttpResponse.Output

[Test]
    public void Valid_input_returns_success_result()
    {
        var result = controller.Test(new TestModel { IsValid = true, IsValid2 = true })
            .AssertResultIs<FormActionResult<TestModel>>();

        var context = controller.ControllerContext;

        Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();

        StringWriter actionResultOutput = new StringWriter();

        mockHttpContext.Setup(x => x.Response.Output).Returns(actionResultOutput);


        context.HttpContext = mockHttpContext.Object;

        result.ExecuteResult(context); 
        // how to verify result? Examine actionResultOutput

    }

All is left to examine actionResultOutput. For example, if your action result is designed to return string "Success" when validation is ok and "Error" when validation failed, compare these strings to actionResultOutput.ToString(). If your result view's generated html is more complex, you can use HtmlAgilityPack to examine output more deeply


You should write a simple unit test of the Test-action, asserting on the returned action result. You shouldn't depend on the MVC framework in your test. Simply create a new instance of TestController and call the Test method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜