问题描述
与相比,我关于模拟的最后一个问题HttpContext ,我不得不将要测试的方法更改为
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);
}
现在我需要弄清楚如何模拟HttpContext.Current.GetOwinContext()
,因此,我可以为Set()
方法编写存根,或者通常能够测试此特定行.我怎样才能做到这一点?
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..
由于GetOwinContext()
返回一个接口,所有您需要做的就是将该调用与方法分开,这样做有两个问题:
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()
由属性类拥有. -
GetOwinContext()
是静态方法.
- The method under test(
OnActionExecuting()
is owned by an attribute class. GetOwinContext()
is a static method.
我能为您提供的2种最佳解决方案是:
The best 2 solutions that I can offer you is:
- 使用诸如MsFakes,Typemock Isolator之类的代码挥舞工具,而不是基于RhinoMocks的基于代理的工具.
- 将
GetOwinContext()
提取为虚拟方法,然后使用PartialMock技术(该技术通常用于抽象类):
- Use code waving tool like MsFakes, Typemock Isolator and etc, instead of proxy based tool like RhinoMocks.
- Extract
GetOwinContext()
to a virtual method and then use PartialMock technique(This technique is usually in use for abstract classes):
让我们说MyCustonAttributte
是您的属性:
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();
}
}
那么您的UT将是:
[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)));
}
这篇关于如何使用Nunit和RhinoMocks模拟HttpContext.Current.GetOwinContext()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!