【发布时间】:2019-10-03 11:42:02
【问题描述】:
我正在为我们的 C# 7 应用程序编写测试,并努力模拟扩展方法。我正在使用 TypeMock 8.6.10.3。
这是一个简化的例子:
internal class InnerClass
{
private readonly string _description;
public InnerClass(string description)
{
_description = description;
}
public string GetDescription()
{
return _description;
}
}
internal class OuterClass
{
public void DoSthWithExtension(int someNumber)
{
var innerClass = new InnerClass("InnerClassDescription");
innerClass.Extension(someNumber);
}
}
internal static class Extensions
{
public static void Extension(this InnerClass innerClass, int someNumber)
{
var d = innerClass.GetDescription();
}
}
public void TestExtension()
{
// I want to fake the method "InnerClass.Extension()"
// which is called by "OuterClass.DoSthWithExtension()".
// I don't have access to the InnerClass instance though.
// So unfortunately I have to fake them all.
var fakedInnerClasses = Isolate.Fake.AllInstances<InnerClass>();
Isolate.WhenCalled(() => Extensions.Extension(fakedInnerClasses, 11)).WithExactArguments().DoInstead(
c =>
{
// The test doesn't go in here. The second parameter is correct,
// the first one obviously not. But what is expected as a first parameter then?
var oc2 = new OuterClass();
// Here I call InnerClass.Extension() again.
// The test should now go into the faked method underneath.
oc2.DoSthWithExtension(22);
});
Isolate.WhenCalled(() => Extensions.Extension(fakedInnerClasses, 22)).WithExactArguments().DoInstead(
c =>
{
// As above, the test code doesn't go in here.
});
// In here an instance of InnerClass is created and
// InnerClass.Extension(11) is called.
var oc1 = new OuterClass();
oc1.DoSthWithExtension(11);
}
作为扩展方法的this 参数,我选择了InnerClass 的伪造实例。这就是我认为需要的。但是 TypeMock 并没有把我带入伪造的方法。显然它的参数错误。但是我应该选择哪一个呢?
【问题讨论】:
-
在这种情况下不要伪造扩展方法。你知道扩展方法调用了什么。太假了。
-
感谢您的快速回复。在我的例子中,这将是 InnerClass.GetDescription()。但我怎么能假呢?该方法不是静态的,我没有 InnerClass 的实例。
-
@telandor 创建一个包含
GetDescription()的接口并创建一个实现该接口的假类。 -
@telandor 我根据您对问题当前状态过度简化的评论删除了我的答案。如果没有 minimal reproducible example 澄清您的具体问题或其他详细信息以准确突出所做的工作,将很难重现问题以更好地了解实际问题是什么。删除的答案将基于提供的信息。
-
套用我读过的一篇文章 虽然 Typemock Isolator 使您能够测试设计不佳的代码,但这并不是阻止正确软件设计的绿灯。您仍然需要以良好的原则设计您的应用程序。
标签: c# unit-testing typemock