2011-04-04 72 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