0
我正在對使用Monorail v1.0.3編寫的舊版Web應用程序進行一些維護。我想單元測試一個使用RenderText()的動作。我如何在我的測試中提取內容?從controller.Response.OutputStream讀取不起作用,因爲響應流要麼在PrepareController()中沒有正確設置,要麼在RenderText()中關閉。單元測試Monorail的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 + " }");
}
實例測試(使用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);
}