【发布时间】:2014-06-08 05:53:54
【问题描述】:
下面是动作方法的一段代码:
private static IEnumerable<SelectListItem> GetProductTypes()
{
System.Text.RegularExpressions.Regex filter = new System.Text.RegularExpressions.Regex("Prodcut1|Prodcut2|Prodcut3");
var prodtypes = from ProdType e in Enum.GetValues(typeof(ProdType))
where filter.IsMatch(e.ToString())
select new { Id = (int)e, Name = e.ToString() };
if (prodtypes != null)
{
return prodtypes .Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
}
return new List<SelectListItem>();
}
其中:ProdType 是枚举。其中包含一些产品类型及其值。
我已经为该方法编写了单元测试:-
[TestMethod]
public void GetProductTypes_Test()
{
//Arrange
PrivateType pvtType = new PrivateType(typeof(ProductController));
//Act
var actual = (IEnumerable<SelectListItem>)pvtType.InvokeStatic("GetProductTypes");
//Assert
Assert.IsNotNull(actual);
Assert.IsInstanceOfType(actual, typeof(IEnumerable<SelectListItem>));
Assert.AreEqual(3, actual.ToList().Count); //here : 3 = Product1,Product2,Product3
}
但是当我通过代码覆盖率选项检查它的代码覆盖率时,它没有覆盖下面的代码行:-
return new List<SelectListItem>();
谁能建议我在这里做错了什么?是的,这是我正在测试的私有方法。因为我想测试所有私有方法。
【问题讨论】:
-
该行永远不会被覆盖,因为
Select本身永远不会返回null。 -
许多开发人员会不同意您对私有方法的测试。它们是内部实现,应该可以随意更改。您应该只测试应用程序的公开可见表面。在此过程中,私有方法将通过其效果进行间接测试。
-
将来你会因为测试这样的私有方法而遭受巨大的痛苦,特别是如果你曾经对它们的名字进行一些重构......
标签: c# unit-testing asp.net-mvc-4 moq private-members