C# 7 how to unit test local functions [duplicate]

此生再无相见时 提交于 2019-12-01 22:33:59

问题


I've been looking at some articles about local functions, and the one sentence states:

Local functions are defined within a method and aren't available outside of it

So given the below code example is there any way to unit test the square method?

int SumAndSquare(int x, int y)
{
    var sum = x + y;
    return square(sum);

    int square(int z)
    {
        return z * z;
    }
}

回答1:


In general you can't in a maintainable way for non-trivial local functions (reason explained in a comment to this response). A local function that uses variables of the method where it is defined (so a non-trivial one, ones that don't use local variables could be private methods) has a special parameter containing these variables. You can't easily recreate this parameter → you can't call it.

It can be easily seen in TryRoslyn (how much I love TryRoslyn! I use it very often 😁)

int Foo()
{
    int b = 5;
    return valueofBplusX(5);

    int valueofBplusX(int x)
    {
        return b + x;
    }
}

is translated in something like:

[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;
}

You see the <>c__DisplayClass0_0 that contains the b local variable, and the <Foo>g__valueofBplusX0_0 that receives as the second argument a ref C.<>c__DisplayClass0_0 ptr?

On top of this, I'll add a quote of Keith Nicholas: Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.



来源:https://stackoverflow.com/questions/42715550/c-sharp-7-how-to-unit-test-local-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!