Visual Studio允许通过自动生成的访问器类对私有方法进行单元测试.我编写了一个成功编译的私有方法的测试,但它在运行时失败了.一个相当小的代码和测试版本是:
//in project MyProj
class TypeA
{
private List<TypeB> myList = new List<TypeB>();
private class TypeB
{
public TypeB()
{
}
}
public TypeA()
{
}
private void MyFunc()
{
//processing of myList that changes state of instance
}
}
//in project TestMyProj
public void MyFuncTest()
{
TypeA_Accessor target = new TypeA_Accessor();
//following line is the one that throws exception
target.myList.Add(new TypeA_Accessor.TypeB());
target.MyFunc();
//check changed state of target
}
Run Code Online (Sandbox Code Playgroud)
运行时错误是:
Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type …Run Code Online (Sandbox Code Playgroud) 我想暴露WebClient.DownloadDataInternal方法,如下所示:
[ComVisible(true)]
public class MyWebClient : WebClient
{
private MethodInfo _DownloadDataInternal;
public MyWebClient()
{
_DownloadDataInternal = typeof(WebClient).GetMethod("DownloadDataInternal", BindingFlags.NonPublic | BindingFlags.Instance);
}
public byte[] DownloadDataInternal(Uri address, out WebRequest request)
{
_DownloadDataInternal.Invoke(this, new object[] { address, out request });
}
}
Run Code Online (Sandbox Code Playgroud)
WebClient.DownloadDataInternal有一个out参数,我不知道如何调用它.救命!
我有一个私有方法,如下所示:
int void SomeMethod(ref string theStr)
{
// Some Implementation
}
Run Code Online (Sandbox Code Playgroud)
如何为这种方法编写单元测试用例.
如果这是重复的,我很抱歉。我被赋予了为该方法添加一些覆盖范围的任务,并被告知要模拟私有List<string>财产。我的问题是:有没有办法测试私有字段?
我找到的解决方案是添加新的构造函数只是为了注入这个私有列表。我不确定这是否是正确的方法,所以任何帮助将不胜感激。
public class Class1
{
public Class1(List<string> list)//This is just for Unit Testing
{
list1 = list;
}
private readonly InjectRepository _repository;
//
public Class1(InjectRepository repository)//This is the actual constructor
{
_repository = repository;
}
private List<string> list1 = new List<string>();
public void Do_Complex_Logic()
{
//list1 will be set with items in it
//Now list1 is passed to some other instance
}
}
Run Code Online (Sandbox Code Playgroud)