I have a piece of code that is intended to act as middleware in charge logging timestamps before and after the execution of an arbitrary piece of code, as well as catching any exception it may throw, logging them and rethrowing them. I'm stuck trying to engineer a test that makes sure the middleware does not affect the stacktrace the original code threw.
I've tried this so far
[Fact]
public async Task The_Middleware_Must_Rethrow_Any_Exception_Thrown_By_The_Next_Middleware()
{
var middleware = new ErrorMiddleware();
_testSubject = new RequestLoggerMiddleware(middleware);
try
{
await _testSubject.Invoke(_mockContext.Object);
} catch (Exception ex)
{
Assert.Same(ex, middleware.ThrownException);
Assert.Equal(ex.StackTrace, middleware.ThrownException.StackTrace);
return;
}
Assert.True(false, "The middleware did not rethrow the exception");
}
private class ErrorMiddleware : OwinMiddleware
{
public Exception ThrownException { get; }
public ErrorMiddleware() : base(null)
{
ThrownException = new Exception(TestExceptionMessage);
}
public override Task Invoke(IOwinContext context)
{
throw ThrownException;
}
}
It seems to work initially, but if I make RequestLoggerMiddleware
run throw ex;
on its catch (Exception ex)
block (rewriting the stacktrace in the process) the test will still pass, even though it shouldn't at all.