Compared to my last question on Mocking the HttpContext, I had to change the method being tested to
public override void OnActionExecuting(HttpActionContext actionContext)
{
HttpContext.Current.GetOwinContext().Set("RequestGUID", NewId.NextGuid());
base.OnActionExecuting(actionContext);
}
Now I need to figure out how to mock the
HttpContext.Current.GetOwinContext()
,
So I could write a stub for the Set()
method, or generally being able to test this particular line. How can I do this?
I have read this article, but in your case, I think that doing such a thing would be an overkill..
Since GetOwinContext()
return an interface all you have to do is to separate this call from the method, doing such a thing has 2 problems:
OnActionExecuting()
is owned by an attribute class.GetOwinContext()
is a static method.The best 2 solutions that I can offer you is:
GetOwinContext()
to a virtual method and then use PartialMock technique(This technique is usually in use for abstract classes):Let's say that MyCustonAttributte
is your attribute:
public class MyCustonAttributte : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
GetOwinContext().Set("RequestGUID", Guid.NewGuid());
base.OnActionExecuting(actionContext);
}
public virtual IOwinContext GetOwinContext()
{
return HttpContext.Current.GetOwinContext();
}
}
Then your UT will be:
[Test]
public void New_GUID_should_be_added_when_OnActionExecuting_is_executing()
{
//arrange section:
const string REQUEST_GUID_FIELD_NAME = "RequestGUID";
var owinContext = MockRepository.GenerateStub<IOwinContext>();
var target = MockRepository.GeneratePartialMock<MyCustonAttributte>();
target.Stub(x => x.GetOwinContext())
.Return(owinContext);
//act:
target.OnActionExecuting(new HttpActionContext());
//assert section:
owinContext.AssertWasCalled(x => x.Set(Arg<string>.Is.Equal(REQUEST_GUID_FIELD_NAME),
Arg<Guid>.Is.NotEqual(Guid.Empty)));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With