Domanda

Sto facendo un po 'di manutenzione su una vecchia applicazione web scritta in monorotaia v1.0.3. Voglio testare unità un'azione che utilizza RenderText (). Come estraggo il contenuto nel mio test? Leggere da Controller.Response.OutputStream non funziona, poiché il flusso di risposta non è impostato correttamente in preparazioni () o è chiuso in rendertext ().

Azione di esempio

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

Esempio di test (usando 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 );
}
È stato utile?

Soluzione

Oltrepassare BaseControllerTest.BuildResponse() e fornisci il tuo simulazione di IMockResponse Costruito con Moq.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top