1

Is it possible to test the nested methods in C# 7.0 through xunit framework? For example, I have such simple nested method Func2():

// C# 7.0, LINQPad 5

void Func1(){
    var name = "Bob";
    Console.WriteLine($"Hello, {name}!");

    void Func2(ref string n) { 
        n = "Super " + n;
        Console.WriteLine($"How are you, {n}?");
    };

    Func2(ref name);

    Console.WriteLine($"Hello again, {name}!");
}

Func1();
Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • 4
    You shouldn't really be testing local methods, just test the outer ones. If the logic inside the local method is complex, it should be extracted out anyway. – DavidG Jul 21 '18 at 10:00
  • By the way, the ref string n is totally unnecessary. The local function has access to the outer method's variables. Setting `name = "Super " + name` and ditching the parameters to `Func2` would do exactly the same thing. Example here: https://sharplab.io/#v2:D4AQDABCCMDcCwAoEBmKAmCBhCBvJEhUaMAbFACxTQAcAFAJR4FGsuuEBuAhgE4QA7bgFsAphAC8EAEQAhAPYAjaQkQciMAJx0AJNIASogDZH5AGjxCxAXwCE0hqvYcQVLAAtuAgOaiAkgAujHgQzuqEVuJS0gDKAK4ADqL80hAA1IIioqrhLtDaevryAO4QfOIAnvJxFriR1gD8Djnh1k5q4R5evoGM7blaugbGpmXe3ACWArX19o5hRM7WSNZAA=== (Sharplab has issues with functions named `FuncX` so I've changed the name) – pinkfloydx33 Jul 21 '18 at 10:37
  • @pinkfloydx33 without `ref` the copy of value will be used at this example. – Andrey Bushman Jul 21 '18 at 11:30
  • Compiler creates a genrated class with a field for the captured locals variables. Then, it actually translates the method into one that accepts that compiler generated class by reference. Then you change the field value. Check out the example I posted. Try the different drop downs in the right pane and you'll see the generated IL or the special, "compiled c#" view. Also the link demonstrates exactly what I said in the result view. Try it. – pinkfloydx33 Jul 21 '18 at 13:04

0 Answers0