我正在ASP.NET MVC 4应用程序中对我的一个动作方法进行单元测试。
问题是该控制器的action方法中有一个私有属性.Below是私有属性和方法的代码: -
私有财产:
private int ProductId
{
get { return Convert.ToInt32(System.Web.HttpContext.Current.Session["FKProductID"]); }
set { System.Web.HttpContext.Current.Session["FKProductID"] = value; }
}
方法:
public ActionResult GetDetails(string Name, int area, int ProdCategoryId = 0)
{
ProductCategoryViewModel model = new ProductCategoryViewModel
{
Area= area,
FKProductID = ProductId, //private property
};
else if (model.FKProductID > 0)
{
ProductDto product= ProductService.GetProductDetails(model.FKProductID);
}
单元测试方法代码:
public void SelectProductTest()
{
// Act
var result = controller.GetDetails(name,area, prodcatid) as PartialViewResult;
}
因为我在测试方法中传递了三个必需的参数,但是我在私有财产地方遇到问题(当控件丰富的时候)。
有谁能让我知道如何应对这种情况?
答案 0 :(得分:0)
无法通过设计从外部访问私人代码 - 这是private
关键字的全部内容。所以没有办法测试它。
相反,通常的方法是将您的属性声明为internal
,然后通过InternalVisibleTo属性授予您的测试程序集访问权限。这样,您就不会破坏封装,因为internal
成员在其他方面的行为与private
成员完全相同。
答案 1 :(得分:0)
您可以使用反射来获取此数据:
How do I test a private function or a class that has private methods, fields or inner classes?
不同的语言/技术,但方法相同。
在.Net上:Get private Properties/Method of base-class with reflection
真实环境:
我们接管了一组由学生设计和实施的项目。没有文档。作者很久以前就逃脱了。客户希望通过向后兼容性扩展功能。您被迫进行无法保持向后兼容性的测试。好吧,这迟早需要测试私有变量。您对他们进行了测试以了解该项目,并发现您尚未将其破坏。
对我来说,不应该说测试应该检查私有财产对我来说是胡说八道。
通过使用“ CodeContract”方法编写缺少的测试并使用陷阱并实现要求等,将使您掌握项目,否则您将走错方向。
https://www.macs.hw.ac.uk/~hwloidl/Courses/F21SC/CodeContracts_UserManual.pdf
对不起,我的英语。