我一直在看一些关于局部函数的文章,其中一句话是这样的:
Local functions are defined within a method and aren't available outside of it
那么给出下面的代码示例是否有任何方法可以对 square
方法进行单元测试?
int SumAndSquare(int x, int y)
{
var sum = x + y;
return square(sum);
int square(int z)
{
return z * z;
}
}
一般来说,您不能以可维护的方式处理非平凡的局部函数(原因在对此回复的 comment 中解释)。使用定义它的方法的变量的局部函数(所以一个不平凡的函数,不使用局部变量的函数可能是私有(private)方法)有一个包含这些变量的特殊参数。您无法轻松地重新创建此参数 → 您无法调用它。
很容易在TryRoslyn中看到(我多么喜欢 TryRoslyn!我经常使用它😁)
int Foo()
{
int b = 5;
return valueofBplusX(5);
int valueofBplusX(int x)
{
return b + x;
}
}
翻译成这样:
[CompilerGenerated]
[StructLayout(LayoutKind.Auto)]
private struct <>c__DisplayClass0_0
{
public int b;
}
private int Foo()
{
C.<>c__DisplayClass0_0 <>c__DisplayClass0_ = default(C.<>c__DisplayClass0_0);
<>c__DisplayClass0_.b = 5;
return C.<Foo>g__valueofBplusX0_0(5, ref <>c__DisplayClass0_);
}
[CompilerGenerated]
internal static int <Foo>g__valueofBplusX0_0(int x, ref C.<>c__DisplayClass0_0 ptr)
{
return ptr.b + x;
}
你看到 <>c__DisplayClass0_0
包含 b
局部变量,以及 <Foo>g__valueofBplusX0_0
接收作为第二个参数的 ref C.<>c__DisplayClass0_0 ptr
?
在此之上,我将添加 Keith Nicholas 的引用: 是的,不要测试私有(private)方法....单元测试的想法是通过其公共(public)“API”测试单元。