NUnit:如何在 C# 中使用“ref”参数测试私有方法
我有一个如下所示的私有方法:
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
如何为此方法编写单元测试用例。
I have a private method like below:
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
how to write the unit test case for this method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个方法是 void 但带有一个 ref 参数似乎有点毫无意义。让它返回一个字符串可能是有意义的:
我们还将其设置为
internal
并在 AssemblyInfo.cs 文件中指定InternalVisibleTo
属性:这样
SomeMethod
> 的行为就像它是内部的(即在其程序集外部不可见),但 Test.Assembly 除外,它将把它视为public
。单元测试非常简单(无论它是否采用
ref
参数)。Seems a bit pointless that a method is void but takes a
ref
parameter. It would probably make sense to make it return a string:We also make it
internal
and specifyInternalVisibleTo
attribute in AssemblyInfo.cs file:This way
SomeMethod
will behave as though it's internal (i.e. not visible outside its assembly) except for Test.Assembly, which will see it aspublic
.The unit test is pretty trivial (regardless of whether or not it takes a
ref
parameter).我通常将方法保护起来并提供一个可测试的继承类。例如:
我认为您会找到“您不应该测试私有方法”的答案,但在某些情况下,我发现它对于获取一些棘手的功能很有用。但是,我还发现,在这些情况下,最好将函数提取到它自己的单独的可测试类中。 ymmv。
I usually make the method protected and provide a testable class that inherits. For example:
I think you'll find answers that say "you shouldn't test private methods", but there are cases where I've found it to be useful to get at some tricky functionality. But then, I've also found that in these situations it's better to extract the function into it's own separate testable class. ymmv.
我的问题是如何为具有 ref 参数的私有方法编写单元测试用例。
有人说改变实施,这是不可能的。可能我在代码片段中给出了一些错误的实现,但这不是我的意图。
有人说不需要测试私有方法。但在某些情况下,需要测试这些方法,例如在某些安全代码中。
答案是:我需要使用反射并从 nunit 设置 setnamedparameterAction。
我需要明确指定特定参数是 ref。
My Question was how to write the unit test case for the private method which is having the ref parameter.
Some of says that change the implementation, it is not possible. might be i have given some wrong implementation in code snipt but that was not my intension.
Some says that no need to test the private method. but in some scenario, it is required to test those method such as in some safety code.
Answer is: I need to use the reflection and set the setnamedparameterAction from the nunit.
i need to specify explicitly that perticular parameter is ref.
如果测试它如此重要,也许您应该将其公开并完成它。 (尽管我意识到这并不能完全回答你的问题)。
并不是每个人都同意仅仅为了测试而公开某些内容,但我认为这比某些替代方案更好。
If it's that important to test it, maybe you should just make it public and be done with it. (Although I realise that doesn't exactly answer your question).
Not everyone would agree with making something public just for testing, but I think it's better than some of the alternatives.