簡體   English   中英

通過調用包裝HttpContext的靜態類的單元測試類

[英]Unit Testing a class with a call to a Static class wrapping an HttpContext

我已經在C#/ ASP.Net Web項目中添加了用於單元測試的方法。 該方法已被其他人修改,可以在包裝HttpContext的類上添加對靜態方法的調用(以添加某些會話狀態),但是在測試期間我沒有HttpContext,因此拋出了空引用異常。 任何想法如何解決這個問題? 如果可以的話,我不想對生產代碼進行太多更改。

被測方法:

public int MethodUnderTest() 
{
    ...
    // Added line which breaks the tests
    StaticClass.ClearSessionState();
}

在StaticClass中:

public void ClearSessionState()
{
    HttpContext.Current.Session["VariableName"] = null;
}

這將引發NullReferenceException因為在測試過程中HttpContext.Current為null。

就使用HttpContext.Current單元測試方法而言,您幾乎處於死胡同。 正確的方法是修改此代碼以使用構造函數注入:

private readonly HttpContextBase _context;
public Foo(HttpContextBase context)
{
    _context = context;
}

public void ClearSessionState()
{
    _context.Session["VariableName"] = null;
}

現在,您可以在單元測試中模擬此HttpContextBase

您可以在調用StaticClass.ClearSessionState()行之前使用模擬/存根對象設置HttpContext.Current。

您可以在生產代碼中進行自己的靜態“注入”,如下所示:

public static class StaticClass {
    public void ClearSession() {
        TheContext["VariableName"] = null;
    }

    public static HttpContextBase TheContext{
        get { 
            if (_context == null)
                _context = new HttpContextWrapper(HttpContext.Current);
            return _context; }
        set { _context = value; }
    }
}

然后,實際測試變得非常簡單,只需在測試之前將TheContext屬性設置為存根實例即可。 例如,在Moq中,可以用一行設置這樣的存根:

StaticClass.TheContext = new Mock<HttpContextBase>(){DefaultValue = DefaultValue.Mock}.Object;

最后,我可以只刪除對StaticClass.ClearSessionState()的調用,但感謝您的所有回答。 有用的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM