测试与“裁判”参数的私有方法我有类似下面的私有方法:NUnit的:如何在C#
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
如何编写单元测试的情况下这种方法。
测试与“裁判”参数的私有方法我有类似下面的私有方法:NUnit的:如何在C#
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
如何编写单元测试的情况下这种方法。
似乎有点毫无意义,一种方法是无效的,但采取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
。
单元测试非常简单(不管它是否需要参数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);
}
我通常使该方法受到保护并提供一个继承的可测试类。例如:
class Foo
{
protected void SomeMethod(ref string theStr) { ... }
...
}
class TestableFoo
{
public void TestableSomeMethod(ref string theStr)
{
base.SomeMethod(...);
}
...
我想你会发现答案是说:“你不应该测试私有方法”,但也有在那里我发现它是得到一些棘手的功能有用的情况。但是,我还发现,在这些情况下,最好将函数提取到它自己单独的可测试类中。因人而异。
我的问题是如何编写具有ref参数的私有方法的单元测试用例。
有些说改变执行,这是不可能的。可能是我在代码片段中给了一些错误的实现,但那不是我的意图。
有人说不需要测试私有方法。但在某些情况下,需要测试这些方法,如某些安全代码。
答案是:我需要使用反射并从nunit中设置setnamedparameterAction。 我需要明确指出,特定的参数是ref。
如果测试它很重要,也许你应该公开并完成它。 (虽然我意识到这并不完全回答你的问题)。
不是每个人都会同意公开某些东西来进行测试,但我认为它比一些替代品更好。
+1:很好。 – Rob 2010-07-15 06:51:27
感谢您的宝贵修正,但在这里我只给了一个代码片断,这不是实际的代码。我的意图是了解如何使用ref关键字测试私有方法。 – 2010-07-15 06:53:51
@Nikhil:如果你没有给出代表性的代码,我们不能轻易分辨哪些差异是相关的,哪些不是。 – 2010-07-15 06:56:19