3

I am writing xunit tests for IotEdge custom Module, where I need to Mock ModuleClient.CreateFromEnvironmentAsync() which opens a connection to Edge runtime.

Iot Edge Module code looks like this :

   var amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);
   ITransportSettings[] settings = { amqpSetting };

   // Open a connection to the Edge runtime
   this.ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
  await this.ioTHubModuleClient.OpenAsync();

Unit test code looks like this:

     var amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);
     ITransportSettings[] settings = { amqpSetting };

     var moduleClientMoq = new Mock<ModuleClient>(ModuleClient.CreateFromEnvironmentAsync(settings));  // getting an exception-"System.NotSupportedException: 'Type to mock must be an interface or an abstract or non-sealed class."        

I am getting "System.NotSupported" exception.Please suggest how to mock Module client.

Pooja P N
  • 57
  • 1
  • 6
  • 2
    [Related GitHub issue](https://github.com/Azure/azure-iot-sdk-csharp/issues/110), albeit with DeviceClient. [Mocking static methods](https://stackoverflow.com/questions/5864076/mocking-static-methods) – ProgrammingLlama Sep 18 '19 at 06:50
  • Check this link : https://stackoverflow.com/a/30200039/6049604 , May i know why are you trying to mock sealed class. – Mohit Verma Sep 18 '19 at 09:36
  • I have some of the custom logic present in the init Method of IotEdge Module which requires Mocking of Module. – Pooja P N Sep 18 '19 at 12:27
  • 1
    You could create a thin wrapper class around the SDK, and mock that? – Damon Barry Sep 18 '19 at 14:24

1 Answers1

1

As suggested in the comment and the GitHub issue, you should implement a wrapper around ModuleClient and base your test on this wrapper. As stated in the GitHub issue, the team behind ModuleClient will not implement an interface any time soon ("Only Mock Types That You Own") and you can get other benefits :

  • You know exactly what functionality your application uses from the type
  • You can adapt in case of undesired changes in behavior
  • You can easily mock
Zied
  • 1,696
  • 12
  • 20