【发布时间】:2010-07-15 06:41:02
【问题描述】:
我有一个私有方法,如下所示:
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
如何为这个方法编写单元测试用例。
【问题讨论】:
我有一个私有方法,如下所示:
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(...);
}
...
我认为您会找到“您不应该测试私有方法”的答案,但在某些情况下,我发现它对于获得一些棘手的功能很有用。但是,我还发现,在这些情况下,最好将函数提取到它自己的单独的可测试类中。 ymmv。
【讨论】:
我的问题是如何为具有 ref 参数的私有方法编写单元测试用例。
有人说改变实现,是不可能的。可能是我在代码片段中给出了一些错误的实现,但这不是我的意图。
有人说不需要测试私有方法。但在某些情况下,需要对这些方法进行测试,例如在某些安全代码中。
答案是:我需要使用反射并从 nunit 设置 setnamedparameterAction。 我需要明确指定特定参数是参考。
【讨论】:
如果测试它很重要,也许您应该将其公开并完成它。 (虽然我意识到这并不能完全回答你的问题)。
不是每个人都同意为了测试而公开一些东西,但我认为这比一些替代品要好。
【讨论】: