Unit testing Monorail's RenderText method

Posted by MikeWyatt on Stack Overflow See other posts from Stack Overflow or by MikeWyatt
Published on 2010-03-23T15:22:17Z Indexed on 2010/03/23 16:23 UTC
Read the original article Hit count: 688

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 );
}

© Stack Overflow or respective owner

Related posts about castle-monorail

Related posts about unit-testing