我有一个私有方法,如下所示:
如何为这个方法编写单元测试用例。
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
如何为这个方法编写单元测试用例。
一个方法是void类型但需要使用ref
参数似乎有点毫无意义。将其改为返回一个字符串可能更加合理:
public class FooBar {
internal string SomeMethod(ref string theStr) {
// Some Implementation
return theStr;
}
}
[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);
}
我通常把方法设为 protected 并提供一个可测试的继承类。例如:
class Foo
{
protected void SomeMethod(ref string theStr) { ... }
...
}
class TestableFoo
{
public void TestableSomeMethod(ref string theStr)
{
base.SomeMethod(...);
}
...
我认为你会发现有些答案会说“你不应该测试私有方法”,但是在某些情况下,我发现访问一些棘手的功能很有用。但是,在这种情况下,我也发现将函数提取到自己的单独可测试类中更好。你的情况可能会有所不同。
我的问题是如何为具有引用参数的私有方法编写单元测试用例。
有些人说改变实现,这是不可能的。也许我在代码片段中给出了一些错误的实现,但那不是我的意图。
有些人说不需要测试私有方法。但在某些情况下,需要测试这些方法,例如在某些安全代码中。
答案是:我需要使用反射并从nunit设置setnamedparameterAction。我需要明确指定特定参数是ref。
如果测试很重要,也许你应该将其公开并完成它。尽管我意识到这并没有完全回答你的问题。
并不是每个人都同意仅为测试而公开某些东西,但我认为这比其他一些选择更好。