Let's see at the following statement in Module.ApplicationEndRequest()
method:
context.Response.Write(builder.ToString());
When this code is executed from Unit Test, context.Response
is a mock that you set up in MoqHttpContext.CreateBaseMocks():
MockResponse = new Mock<HttpResponseBase>();
// ...
MockContext.Setup(ctx => ctx.Response).Returns(MockResponse.Object);
You can't expect that you call a Write()
method on a mock and then can read the same data back. Mock is a fake object. Its default implementation of Write()
method does nothing, and passed data is just lost.
To fix the problem, you could setup a callback on Response
mock that will write passed data to a stream and then return it back on read. You are actually very close to it.
In MoqHttpContext
class declare a stream where you will save the data:
public class MoqHttpContext
{
private readonly MemoryStream _outputStream = new MemoryStream();
// ...
}
Then in CreateBaseMocks()
method setup a callback:
public MoqHttpContext CreateBaseMocks()
{
// ...
MockResponse = new Mock<HttpResponseBase>();
MockResponse.Setup(x => x.Write(It.IsAny<string>())).Callback<string>(s =>
{
var data = Encoding.ASCII.GetBytes(s);
_outputStream.Write(data, 0, data.Length);
_outputStream.Flush();
_outputStream.Position = 0;
});
// ...
}
You also should remove a line that sets inputStream
position to 0
in MoqHttpContextExtensions.StreamWrite()
, so that html data that you write in UnitTest1.TestMethod1()
is appended, not overwritten:
public static HttpContextBase StreamWrite(this HttpContextBase httpContextBase, Stream inputStream, string text)
{
if (inputStream == null) inputStream = new MemoryStream();
var streamWriter = new StreamWriter(inputStream);
inputStream.Position = inputStream.Length;
streamWriter.Write(text);
streamWriter.Flush();
// Remove this line
//inputStream.Position = 0;
return httpContextBase;
}
That's it. Now if you check value of responseRead
in the test, you will see that data appended by Http module is there.
UPDATE (Fixing problem with a filter)
There are 3 different issues with current code that prevent correct work of a filter from UT.
You tried handful options for mocking Filter
property, however none of them seems correct. The correct way to mock property getter with Moq is:
MockResponse.SetupGet(response => response.Filter).Returns(filter);
Remove all other statements for mocking response.Filter
, but don't add above statement yet, it's not a final version.
You have following check in Module.ApplicationEndRequest()
method:
if (context.Response.Filter is ResponseSniffer filter)
{
// ...
When UT is executed, context.Response.Filter
is a MemoryStream
not a ResponseSniffer
. Setter that is called in Module
constructor:
context.Response.Filter = new ResponseSniffer(context.Response.Filter);
will not actually affect value returned by Filter
getter because it's a mock that currently always return instance of MemoryStream
that you setup with SetupGet
. To fix this problem you should actually emulate property behavior: save the value passed to setter and return it in the getter. Here is a final setup of response.Filter
property:
Stream filter = new MemoryStream();
MockResponse.SetupSet(response => response.Filter = It.IsAny<Stream>()).Callback<Stream>(value => filter = value);
MockResponse.SetupGet(response => response.Filter).Returns(() => filter);
Make sure you have deleted all other mocks of response.Filter
property.
The final problem that you should fix - is the order of Module
invocations from UT. Currently the order is the following:
httpContext.StreamWrite(httpContext.Response.Filter, html);
// ...
var module = new Module();
module.PreRequestHandlerExecute(mockHttpContext.HttpContext());
But PreRequestHandlerExecute
sets Response.Filter
with an instance of ResponseSniffer
. So when httpContext.StreamWrite
above it is called, httpContext.Response.Filter
holds actually instance of MemoryStream
, not ResponseSniffer
. So the last fix you should make is to change the order of statements in UT body:
// ...
var module = new Module();
module.PreRequestHandlerExecute(mockHttpContext.HttpContext());
httpContext.ResponseWrite(html);
httpContext.StreamWrite(httpContext.Response.Filter, html);
module.ApplicationBeginRequest(mockHttpContext.HttpContext());
module.ApplicationEndRequest(mockHttpContext.HttpContext());
// ...
UPDATE (UT Redesign)
At this point your UT should work. However current test is very cumbersome. The fact that it takes so much time to understand why it does not work proves it. Such tests are very hard to maintain and fix, they become a real pain over time.
Moreover it's rather Integration test than Unit test, because it invokes several of classes with different functionality - ResponseSniffer
and Module
.
You should strongly consider redesign of current test. And the good start is to make separate tests for ResponseSniffer
and Module
classes.
Most valuable test for ResponseSniffer
is the one that verifies that written data is registered in RecordStream
:
[TestClass]
public class ResponseSnifferTests
{
[TestMethod]
public void Write_WritesDataToRecordStream()
{
// Arrange
var inData = new byte[] { 0x01 };
var target = new ResponseSniffer(Mock.Of<Stream>());
// Act
target.Write(inData, 0, inData.Length);
// Assert
target.RecordStream.Position = 0;
var outData = new byte[inData.Length];
int outSize = target.RecordStream.Read(outData, 0, outData.Length);
Assert.AreEqual(inData.Length, outSize);
CollectionAssert.AreEqual(inData, outData);
}
}
As regards Module
class, there are several checks that should be made:
PreRequestHandlerExecute()
sets Response.Filter
with instance of ResponseSniffer
.
ApplicationBeginRequest()
adds Stopwatch
to context.Items
dictionary.
ApplicationEndRequest()
writes request info to the response.
UT approach implies checking of these facts in separate tests. Here are samples of such 3 tests:
[TestClass]
public class ModuleTests
{
[TestMethod]
public void PreRequestHandlerExecuteShouldSetResponseSnifferAsFilter()
{
// Arrange
Stream filter = null;
Mock<HttpResponseBase> httpResponseMock = new Mock<HttpResponseBase>();
httpResponseMock.SetupSet(response => response.Filter = It.IsAny<Stream>()).Callback<Stream>(value => filter = value);
Mock<HttpContextBase> httpContextStub = new Mock<HttpContextBase>();
httpContextStub.SetupGet(x => x.Response).Returns(httpResponseMock.Object);
var target = new Module();
// Act
target.PreRequestHandlerExecute(httpContextStub.Object);
// Assert
Assert.IsNotNull(filter);
Assert.IsInstanceOfType(filter, typeof(ResponseSniffer));
}
[TestMethod]
public void ApplicationBeginRequestShouldStoreStopwatchInContextItems()
{
// Arrange
var items = new Dictionary<string, object>();
Mock<HttpContextBase> httpContextStub = new Mock<HttpContextBase>();
httpContextStub.SetupGet(x => x.Items).Returns(items);
var target = new Module();
// Act
target.ApplicationBeginRequest(httpContextStub.Object);
// Assert
Assert.IsTrue(items.ContainsKey("X-ResponseTime"));
Assert.IsInstanceOfType(items["X-ResponseTime"], typeof(Stopwatch));
}
[TestMethod]
public void ApplicationEndRequestShouldAddRequestInfoToResponse()
{
// Arrange
Mock<HttpRequestBase> httpRequestMock = new Mock<HttpRequestBase>();
httpRequestMock.SetupGet(x => x.FilePath).Returns("/test");
string writtenData = null;
Mock<HttpResponseBase> httpResponseMock = new Mock<HttpResponseBase>();
httpResponseMock.Setup(x => x.Write(It.IsAny<string>())).Callback<string>(s => writtenData = s);
Mock<HttpContextBase> httpContextStub = new Mock<HttpContextBase>();
httpContextStub.SetupGet(x => x.Request).Returns(httpRequestMock.Object);
httpContextStub.SetupGet(x => x.Response).Returns(httpResponseMock.Object);
httpContextStub.SetupGet(x => x.Items).Returns(new Dictionary<string, object> { ["X-ResponseTime"] = new Stopwatch() });
var target = new Module();
// Act
target.ApplicationEndRequest(httpContextStub.Object);
// Assert
Assert.IsTrue(Regex.IsMatch(writtenData, @"Response Size: \d+ bytes<br/>"));
Assert.IsTrue(Regex.IsMatch(writtenData, @"Module request time: \d+ ms"));
}
}
As you see, the tests are pretty simple and straightforward. You don't need those MoqHttpContext
and MoqHttpContextExtensions
with a lot of mocks and helpers anymore. Another benefit - if some of the tests get broken, it's much easier to identify the root cause and fix it.
If you are new to Unit Testing and are looking for good source of info on it, I strongly suggest book The Art of Unit Testing by Roy Osherove.
PreRequestHandlerExecute
theFilter
is still aStream
and not aResponseSniffer