简体   繁体   English

依赖于HttpContext的单元测试

[英]Unit testing with dependency on HttpContext

I need to test some static methods that rely on the current context. 我需要测试一些依赖于当前上下文的静态方法。 Now, I can certainly use the HttpContextWrapper to remove this dependency from my own code. 现在,我当然可以使用HttpContextWrapper从我自己的代码中删除此依赖项。 The problem lies with the 3rd party API I am using in these methods. 问题在于我在这些方法中使用的第三方API。 THEY are relying on the HttpContext and so I can't do anything about that. 他们依赖于HttpContext ,所以我对此无能为力。 However, what I'm trying to do is set the HttpContext with my HttpContextBase . 但是,我想做的是使用HttpContext设置HttpContextBase

So my code looks something like this: 所以我的代码看起来像这样:

public static bool IsSignedUpUser()
{
    //This calls IsSignedUpUser with the production context
    return IsSignedUpUser(new HttpContextWrapper(HttpContext.Current));
}

public static bool IsSignedUpUser(HttpContextBase context)
{
    HttpCookie objCookie = SomeExternalAPIThatReliesOnHttpContextBeingSet();

    return (objCookie != null)
}

What I want to do is something like: 我想做的是这样的:

HttpContext.Current = context; //where context is a mocked HttpContextBase

This way when the 3rd party API is looking in the HttpContext for querystring, cookie values, etc, it doesn't throw a NullReferenceException . 这样,当第三方API在HttpContext查找查询字符串,cookie值等时,它不会抛出NullReferenceException

Why isn't this a dupe? 为什么这不是骗子?

In the code in the question referenced as a dupe, the author looks to be in complete control with no external dependencies. 在该问题的代码中,作者似乎被完全控制,没有任何外部依赖。 I'm using third party libraries that have a dependency on HttpContext , I can't change their method signatures to accept HttpContextBase so I need a way to assign my HttpContextBase to HttpContext . 我正在使用依赖于HttpContext第三方库,我无法更改其方法签名以接受HttpContextBase因此我需要一种将HttpContextBase分配给HttpContext

If this is not possible, and so far I am lead to believe that it isn't, then good answers should suggest how to remove these dependencies. 如果这是不可能的,并且到目前为止,我被认为是不可能的,那么好的答案应该建议如何删除这些依赖项。 500 - Internal Server Error has at least one good suggestion. 500-内部服务器错误至少有一个好的建议。

在我看来,您应该使用注入的自定义接口方法替换对SomeExternalAPIThatReliesOnHttpContextBeingSet的调用,然后可以像其他任何方法一样对其进行模拟。

[EDIT] Per @jessehouwing, "Moles" is now "Fakes", which should improve your Google-fu [编辑]根据@jessehouwing,“痣”现在为“假”,这应该会改善您的Google-fu

Ah, static dependencies...the worse kind. 啊,静态依赖...更糟糕的一种。

It may be overkill, but I would look into perhaps using Moles (or whatever the heck they renamed it to), which will let you override ANY behavior, static, sealed or otherwise; 可能是矫kill过正,但我​​可能会考虑使用Moles (或将其重命名为的任何技巧),它将让您覆盖任何静态,密封或其他方式的行为; here are some links to peruse: 这里是一些细读链接:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM