Search code examples
unit-testingmoqmspec

How do I create a an instance of a type with a private constructor for unit testing?


I need to unit test an event handler that responds to the SerialDataReceived event of System.IO.Ports.SerialPort. This event handler has the signature

void SerialDataReceived(object sender, SerialDataReceivedEventArgs e)

So when my unit test calls into the method, it needs a SerialDataReceivedEventArgs instance. But that object has a private constructor. So how do I get a SerialDataReceivedEventArgs to pass into the method?

I'm sure I must be missing an obvious technique here, I have had a long day... Any advice please?


Solution

  • You can create an instance of the desired type using reflection:

    var args = typeof(SerialDataReceivedEventArgs)
      .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new [] { typeof(SerialData) }, null)
      .Invoke(new object[] { SerialData.Chars });