-1

I am tryin to test a private static method like so:

public void myMethodTest()
        {
            MyClass target = new MyClass();
            PrivateType pt = new PrivateType(target.GetType());
            var x = pt.InvokeStatic("MyMethod");
          //Some type of Assert here
        }

The method also uses a private static variable within its class to check if its null, MyMethod is what im trying to test

private static HashSet<AnotherClass> fakeName{get;set;}

private static void MyMethod()
{
  if (null== fakeName)
  {
    fakeName = new HashSet<AnotherClass>();
  }
}

Thanks guys, if you need more clarification please let me know

In my Test if I do ,

Assert.IsNotNull(x);

the test fails, im just wondering if the method is actually been called , i followed this answer to run this test Stack answer

JohnChris
  • 1,360
  • 15
  • 29
  • 6
    You don't directly test private members. You test the public behavior of the object. That public behavior would internally invoke private members. If the public behavior works, the object works. – David Oct 16 '17 at 15:40
  • 4
    [Don't test internal or private code](http://blog.ploeh.dk/2015/09/22/unit-testing-internals). – Mark Seemann Oct 16 '17 at 15:41
  • yeah I have read all this stuff, and i agree, but some times in life you are asked to do something even if you dont agree, so i have to test them lol – JohnChris Oct 16 '17 at 15:42
  • 1
    If when you call `pt.InvokeStatic("MyMethod");` and there is an error the test will fail (and if there is not it will not). You dont need to assert anything. – Magnus Oct 16 '17 at 15:44
  • @Magnus fair enough, thanks – JohnChris Oct 16 '17 at 15:44
  • @JohnChris: Well, what are you *asserting* with this test? What is this test meant to validate? – David Oct 16 '17 at 15:44
  • @David... hmmm yeah good point.. its just that the method runs with no errors, but maybe thats pretty obvious already – JohnChris Oct 16 '17 at 15:46
  • @JohnChris: Seems reasonable enough then. My arrange/act/assert structures often find the assert part to be nothing more than a comment indicating that the test passes if no exception is thrown. Some unit test frameworks also have ways to assert that explicitly, often as a method decoration. – David Oct 16 '17 at 15:48
  • 2
    But if you know that it should throw exceptions under certain circumstances that is probably what you should test. – Magnus Oct 16 '17 at 15:52

1 Answers1

1

Using Typemock Isolator you can:

public void myMethodTest()
    {
        MyClass target = new MyClass();
        Isolate.Invoke.Method<MyClass>("MyMethod");
        Isolate.Verify.NonPublic.WasCalled(typeof(Dependency), "MyMethod");
    }

but it's commercial.

Gregory Prescott
  • 574
  • 3
  • 10