NUnit:如何在C#中使用“ref”参数测试私有方法

我有一个私有方法,如下所示:

int void SomeMethod(ref string theStr) { // Some Implementation } 

如何为这种方法编写unit testing用例。

似乎有点没有意义,方法是无效的,但需要一个ref参数。 使它返回一个字符串可能是有意义的:

 public class FooBar { internal string SomeMethod(ref string theStr) { // Some Implementation return theStr; } } 

我们还将其设置为internal并在AssemblyInfo.cs文件中指定InternalVisibleTo属性:

  [assembly: InternalsVisibleTo("Test.Assembly")] 

这样SomeMethod行为就好像它是内部的(即在程序集之外不可见),除了Test.Assembly,它会将其视为public

unit testing非常简单(无论是否需要ref参数)。

 [Test] public void SomeMethodShouldReturnSomething() { Foobar foobar = new Foobar(); string actual; foobar.SomeMethod(ref actual); Assert.AreEqual("I'm the test your tests could smell like", actual); } 

我通常使方法受到保护,并提供一个可inheritance的可测试类。 例如:

 class Foo { protected void SomeMethod(ref string theStr) { ... } ... } class TestableFoo { public void TestableSomeMethod(ref string theStr) { base.SomeMethod(...); } ... 

我想你会找到答案,说“你不应该测试私有方法”,但有些情况下我发现它有助于获得一些棘手的function。 但是,我还发现在这些情况下最好将函数提取到它自己独立的可测试类中。 因人而异。

我的问题是如何编写具有ref参数的私有方法的unit testing用例。

有人说改变实施,这是不可能的。 可能是我在代码片段中给出了一些错误的实现,但这不是我的意图。

有人说不需要测试私有方法。 但在某些情况下,需要测试这些方法,例如某些安全代码。

答案是:我需要使用reflection并从nunit设置setnamedparameterAction。 我需要明确指出相关参数是ref。

如果对它进行测试非常重要,那么也许你应该公开并完成它。 (虽然我意识到这并不能完全回答你的问题)。

不是每个人都同意将某些东西公开用于测试,但我认为它比一些替代方案更好。