2011-04-04 70 views
0

我正在爲使用EF 4.0的ASP.MVC 3應用程序編寫單元測試,並且在測試期間遇到System.NullReferenceException問題。我在服務層測試這種方法:單元測試帶字符串屬性問題的NullReferenceException

public IQueryable<Pricing> GetPricing(int categoryID) 
    { 
     var query = from t in _repository.GetAllPricing() 
        where t.FK_Category == categoryID 
        where t.Status.Equals("1") 
        select t; 
     return query; 
    } 

它工作正常。但是當Status等於空,我打電話

svc.GetPricing(1).Count(); 

在測試方法,然後它拋出異常。我使用假存儲庫和其他(空)字符串很好。

我試過用pricing.Status = Convert.ToString(null);而不是pricing.Status = null;,但是這也沒用。

回答

1

問題是你不能在空引用上調用.Equals - 它會像你所經歷的拋出NullReferenceException一樣。現在

public IQueryable<Pricing> GetPricing(int categoryID) 
{ 
    var query = from t in _repository.GetAllPricing() 
       where t.FK_Category == categoryID 
       where t.Status == "1" 
       select t; 
    return query; 
} 
+0

謝謝,檢驗合格:

相反,你可以調用平等運營商。所以當使用Equals和==時?應用程序適用於Equals,只有測試失敗。 – xxviktor 2011-04-04 20:12:19

+0

variable.Equals(other)將工作UNLESS變量是(或可能)爲null。我會堅持==以保證安全。 – 2011-04-04 20:29:37