![](/img/trans.png)
[英]How to write Nunit test for a method which passes an object (C#)
[英]NUnit: How to test a private method with “ref”parameter in 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。
如果測試它很重要,也許你應該公開並完成它。 (雖然我意識到這並不能完全回答你的問題)。
不是每個人都同意將某些東西公開用於測試,但我認為它比一些替代方案更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.