views:

68

answers:

1

I'm doing some maintenance on an older web application written in Monorail v1.0.3. I want to unit test an action that uses RenderText(). How do I extract the content in my test? Reading from controller.Response.OutputStream doesn't work, since the response stream is either not setup properly in PrepareController(), or is closed in RenderText().

Example Action

public DeleteFoo( int id )
{
    var success= false;
    var foo = Service.Get<Foo>( id );
    if( foo != null && CurrentUser.IsInRole( "CanDeleteFoo" ) )
    {
        Service.Delete<Foo>( id );
        success = true;
    }

    CancelView();
    RenderText( "{ success: " + success + " }" );
}

Example Test (using Moq)

[Test]
public void DeleteFoo()
{
    var controller = new FooController ();
    PrepareController ( controller );

    var foo = new Foo { Id = 123 };

    var mockService = new Mock < Service > ();
    mockService.Setup ( s => s.Get<Foo> ( foo.Id ) ).Returns ( foo );
    controller.Service = mockService.Object;

    controller.DeleteTicket ( foo.Id );

    mockService.Verify ( s => s.Delete<Foo> ( foo.Id ) );
    Assert.AreEqual ( "{success:true}", GetResponse ( Response ) );
}

// response.OutputStream.Seek throws an "System.ObjectDisposedException: Cannot access a closed Stream." exception
private static string GetResponse( IResponse response )
{
    response.OutputStream.Seek ( 0, SeekOrigin.Begin );
    var buffer = new byte[response.OutputStream.Length];
    response.OutputStream.Read ( buffer, 0, buffer.Length );
    return Encoding.ASCII.GetString ( buffer );
}
+3  A: 

Override BaseControllerTest.BuildResponse() and provide your mock of IMockResponse built with Moq.

Mauricio Scheffer