Vir Chauhan
Vir Chauhan

Reputation: 11

Response.BinaryWrite() in ASP.Net MVC Test Project

I am stuck in a situation, in which i am creating a test project in ASP.Net MVC, here i am testing a Method which is actually using to download a file, so whenever i am trying to test this method it gives

OutputStream is not available when a custom TextWriter is used

Error in Response.BinaryWrite(), everything is fine except this, can anyone tell me how to resolve this exception, i am using MOQ dll for Mocking, Please suggest me to get rid of this situation.

HttpContext.Current.Response.BinaryWrite()

This is the line which is actually generating exception, now i have a question that- Is this good to test a download method or i have to leave it, if it is good then how to resolve this issue.

Thanks.

Upvotes: 0

Views: 1383

Answers (1)

Andrew
Andrew

Reputation: 5277

If you are writing a unit test you generally don't want to be writing a test that have dependencies that you can't control (e.g. writing to the database, filesystem or output stream). You can also assume that the Response.BinaryWrite does what it is supposed to.

You could do something like this to get around the error you are seeing.

public interface IBinaryWriter 
{
  void BinaryWrite(byte[] buffer);
}

public class ResponseBinaryWriteWrapper : IBinaryWriter
{ 
  public void BinaryWrite(byte[] buffer)
  {
     HttpContext.Current.Response.BinaryWrite(buffer);    
  }
}

This will give you the ability to inject the IBinaryWriter into the class you want to test as a mock and then you can check that BinaryWrite is called with the correct byte array. In your production code you then inject your concrete ResponseBinaryWriterWrapper class.

Upvotes: 1

Related Questions