How to create an instance of DataReceivedEventArgs or populate it with data?

I start the process and redirect the error stream so that it can be parsed and find out what happened. I do it like this:

_proc.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);

Where NetErrorDataHandler has the following signature:

private void NetErrorDataHandler(object sendingProcess, DataReceivedEventArgs errLine)

So far I have had to work with DataReceivedEventArgs, but I'm not sure how to test it. I am currently starting the process I am working with. You cannot create an instance of DataReceivedEventArgs with additional data, so how can I overcome this obstacle? The only way to see how to do it now is to create a process that will work for me. However, this is not the best option for testing.

+3
source share
2

DataReceivedEventArgs?

, DataReceivedEventArgs , , .

. -, :

internal class CustomDataReceivedEventArgs : EventArgs
{

    public string Data { get; set; }


    public CustomDataReceivedEventArgs(string _Data) 
    {
        Data = Data;
    }

    public CustomDataReceivedEventArgs(DataReceivedEventArgs Source) 
    {
        Data = Source.Data;
    }
}

:

    private void NetErrorDataHandler_Implementation(object sendingProcess, 
        CustomDataReceivedEventArgs errLine) 
    {
        //Your actual event handling implementation here...
    }

, :

    private void NetErrorDataHandler(object sendingProcess, 
        DataReceivedEventArgs errLine)
    {
        NetErrorDataHandler_Implementation(sendingProcess, 
            new CustomDataReceivedEventArgs(errLine));
    }

, :

        NetErrorDataHandler_Implementation(new object(),
            new CustomDataReceivedEventArgs("My Test Data"));
+2

, . , , . :

    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");

... , , : -)

+7

Source: https://habr.com/ru/post/1716435/


All Articles