Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock ModuleClient?

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.

like image 497
Pooja P N Avatar asked Dec 03 '25 15:12

Pooja P N


1 Answers

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
like image 62
Zied Avatar answered Dec 06 '25 08:12

Zied