我正在启动一个进程并重定向错误流以便能够解析它并了解发生了什么。我是这样做的:
_proc.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);
其中 NetErrorDataHandler 具有以下签名:
private void NetErrorDataHandler(object sendingProcess, DataReceivedEventArgs errLine)
到目前为止,我必须使用 DataReceivedEventArgs,但我不确定如何测试它。目前我正在运行我正在使用的过程。你不能用额外的数据创建 DataReceivedEventArgs 的实例,那么我该如何克服这个障碍呢?我现在看到如何做到这一点的唯一方法是创建一个可以为我完成工作的流程。但是,这不是用于测试目的的最佳选择。
最佳答案
我刚刚发现可以使用内部构造函数创建对象并设置内部字段。显然,这是不鼓励的,但它适用于短期模拟。这是一个例子:
private DataReceivedEventArgs CreateMockDataReceivedEventArgs(string TestData)
{
if (String.IsNullOrEmpty(TestData))
throw new ArgumentException("Data is null or empty.", "Data");
DataReceivedEventArgs MockEventArgs =
(DataReceivedEventArgs)System.Runtime.Serialization.FormatterServices
.GetUninitializedObject(typeof(DataReceivedEventArgs));
FieldInfo[] EventFields = typeof(DataReceivedEventArgs)
.GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (EventFields.Count() > 0)
{
EventFields[0].SetValue(MockEventArgs, TestData);
}
else
{
throw new ApplicationException(
"Failed to find _data field!");
}
return MockEventArgs;
}
这样使用:
DataReceivedEventArgs TestEventArgs = CreateMockDataReceivedEventArgs("Test");
...这需要一些研究,我认为这是不可能的:-)
关于c# - 如何实例化 DataReceivedEventArgs 或者能够用数据填充它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354308/