Reputation: 7160
I have a simple website that has one page. The function I am unit testing is
public void WriteFileToClient(string fileContent, string fileName)
{
StringWriter stringWriter = new StringWriter();
stringWriter.Write(fileContent);
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.txt", fileName));
Response.Clear();
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
{
writer.Write(stringWriter.ToString());
}
Response.End();
}
When I run my test it says that Response
is not available
Here is my Unit test
[TestMethod]
[TestCategory("Unit")]
public void WriteFileToClient_ShouldSucceedForCorrectInput()
{
//Arrange
Migrate migrate = new Migrate();
Guid g = Guid.Parse("fffe49c1-a838-46bc-b5c6-4e0bbd3e4c32");
string fileContent = migrate.GenerateFlatFileText(g);
string fileName = string.Format("flat file - {0}.txt", g);
//Ask
migrate.WriteFileToClient(fileContent, fileName);
//Assert
migrate.Response.OutputStream.Should().NotBeNull();
migrate.Response.ContentType.Should().Be("text/plain");
migrate.Response.Headers.Should().HaveCount(1);
}
Any suggestions on how to mock the response? honestly I don't understand why the Response
object is not available, my Migrate
class inherits Page
and to my understanding should has the Response
included
Upvotes: 0
Views: 2526
Reputation: 17010
The Response object is part of System.Web, which is a strong indicator it runs inside a web server. You are running a "unit test" on web code without invoking a web server. Can you guess why it might be failing?
UI is not normally something you can easily unit test, if at all. An exception is a controller in MVC, but the controller must be isolated from dependencies to be unit tested beyond "did it call the correct view". When you start dealing with tests on things like response stream, you need to bring up the code in the context of a web server. This means the actual code with Response has to be tested using an HTTP Request and then examining the response. This is more of an integration test than a unit test, unless you mock up the dependency.
Make sense?
Upvotes: 3