模拟一个私人领域 [英] Mocking a private field
问题描述
我知道有人问过类似的问题,但我没有找到明确的解决方案.我正在尝试从一个大类中模拟一个私有字段.私有字段是通过一些较早的方法实例化的,我正在尝试对引用该字段的后一种方法进行单元测试.
I know a similar question has been asked but I have not found a clear solution. I'm trying to mock a private field from a large class. The private field gets instantiated in some earlier method and I'm trying to unit test a latter method which references the field.
所以我的课堂上有一个更早的方法:
So I have an earlier method in my class:
public bool validateAll(ref DataEntry[] oEntries, string sMediaPlanId, ITemplateGenerator oTempGen)
{
...
// private field that I am trying to mock
this._sMediaPlanObjective = (MPWrapper.Instance).getMediaPlanObjective(sMediaPlanId);
...
}
我正在尝试对引用私有字段的方法进行单元测试:
And I'm trying to Unit test a method that references the private field:
public bool validateFlightObjective(ref MPDataEntry oEntry)
{
...
string entryFlightObjective = oEntry.getFlightObjective();
string mediaPlanObjective = this._sMediaPlanObjective;
if (entryFlightObjective != mediaPlanObjective)
{
return false;
}
...
return true;
}
鉴于我有一个很大的类,而这只是我要测试的一种方法,有没有一种方法可以模拟这个私有字段?我是缺少基本的东西还是应该考虑其他方法?
Given that I have a large class and this is just one method I want to test, is there a possible way to just mock this private field? Am I missing something basic or should I consider some other approach?
推荐答案
您不能模拟任何私有,静态或本质上不可替代的 (这是免费的模拟库限制).
You can't mock anything that's private, static, or essentially - non overridable (this comes as a free mocking libraries limitation).
在这种情况下(当private
成员已被进行测试时),您通常要做的是将private
成员提取到一个单独的类中,并
What you usually do in such situations (when it appears that private
member has to be tested), is extracting your private
member to a separate class and inject it to tested class as a dependency.
在您的情况下,您实际上需要提取创建_sMediaPlanObjective
的代码,这是以下行:
In your case, you actually need to extract code that creates _sMediaPlanObjective
, which is this line:
this._sMediaPlanObjective =
(MPWrapper.Instance).getMediaPlanObjective(sMediaPlanId);
提供getMediaPlanObjective
方法的
对象应注入到测试的类中.如果这样做,您可以简单地模拟该对象,并告诉它返回模拟的_sMediaPlanObjective
版本.
Object that provides getMediaPlanObjective
method should be injected to your tested class. If you do so, you can simply mock that object and tell it to return mocked version of _sMediaPlanObjective
.
这篇关于模拟一个私人领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!