Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate DataReceivedEventArgs or be able to fill it with data?

Tags:

c#

.net

process

I'm starting a process and redirecting the error stream to be able to parse it and know what happened. I'm doing it this way:

_proc.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);

Where NetErrorDataHandler has the following signature:

private void NetErrorDataHandler(object sendingProcess, DataReceivedEventArgs errLine)

So far I have to work with DataReceivedEventArgs, but I'm not sure how to test it. Currently I'm running the process I'm working with. You can`t create instance of DataReceivedEventArgs with additional data, so how can I overcome this obstacle? The only way I see how to do this now is to create a process that would do the work for me. However, this isn't the best option for testing purposes.

like image 955
Yaroslav Yakovlev Avatar asked Dec 29 '22 16:12

Yaroslav Yakovlev


1 Answers

What data does your application use out of DataReceivedEventArgs?

Your best solution may be to wrap DataReceivedEventArgs with a class that you are able to inject data into for testing and then pass that to an implementation method instead of doing all of your work inside of the current event handler.

Let me show you. First, create your custom wrapper class:

internal class CustomDataReceivedEventArgs : EventArgs
{

    public string Data { get; set; }


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

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

Next, move your event handler impelmentation into the new method:

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

Finally, set your event handler to do nothing but call the new method:

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

Now, you can test your implementation by calling your implementation like this:

        NetErrorDataHandler_Implementation(new object(),
            new CustomDataReceivedEventArgs("My Test Data"));
like image 67
Robert Venables Avatar answered Jan 01 '23 06:01

Robert Venables