I am currently testing private method this way (using nunit
):
class Foo
{
private int Identity(int n) => n;
}
[TestFixture]
class MyTests
{
[Test]
public void TestFoo()
{
var myFoo = new Foo();
var identityMethod = myFoo.GetType().GetMethod("Identity", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.That(identityMethod.Invoke(myFoo, new []{ (object)42 }), Is.EqualTo(42));
}
}
My team does not like this, because put the method name as a string prevent this method to be renamed, if we want to do refactoring through automatic tools.
I tried to replace the name with nameof
, but:
Foo.Indentity(int) is inaccessible due to its protection level
(By the way, this is strange in my opinion that such an operator respects the privacy protections).
So, can I test private methods without sacrificing possible refactoring?
I was proposed to make the private methods protected and inherit the class with the class test, but this does not satisfy me.
Disclaimer: I know that some people think that private method should not be tested, but this is not the point here. Please do not transform this question into a debate about this.