0

我正在对用 Monorail v1.0.3 编写的旧 Web 应用程序进行一些维护。我想对使用 RenderText() 的操作进行单元测试。如何提取测试中的内容?从 controller.Response.OutputStream 读取不起作用,因为响应流在 PrepareController() 中没有正确设置,或者在 RenderText() 中关闭。

示例操作

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

示例测试(使用最小起订量)

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

1 回答 1

3

覆盖BaseControllerTest.BuildResponse()并提供您IMockResponse使用 Moq 构建的模拟。

于 2010-03-23T16:21:24.383 回答