Generic NSubstitute Method

I have the following method signature in the interface:

public interface ISettingsUtil { T GetConfig<T>(string setting, dynamic settings); } 

Which I tried to make fun of:

 var settingsUtil = Substitute.For<ISettingsUtil>(); var maxImageSize = settingsUtil.GetConfig<long>("maxImageSize", Arg.Any<dynamic>()).Returns(100L); 

This throws a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException exception in the second line:

'long' does not contain a definition for 'Returns'

Any thoughts on how to mock T GetConfig<T>(string setting, dynamic settings) correctly?

+4
source share
2 answers

NSubstitute does not work with members using dynamic . ( github issue )

+3
source

For those who are still struggling with this, you can actually make fun of the dynamics at NSubsitute, it just needs to jump through some minor hoops. See the following case of bullying calls to the signalR client hub.

Important line:

 SubstituteExtensions.Returns(_hubContext.Clients.All, _mockClient); 

To mock the dynamics, I created an interface with the methods I want to listen to. Then you need to use SubstituteExtensions.Returns, not just a chain. Returns at the end of the object.
If you do not need to check anything, you can also use an anonymous object.

The following is a sample full code:

 [TestFixture] public class FooHubFixture { private IConnectionManager _connectionManager; private IHubContext _hubContext; private IMockClient _mockClient; [SetUp] public void SetUp() { _hubContext = Substitute.For<IHubContext>(); _connectionManager = Substitute.For<IConnectionManager>(); _connectionManager.GetHubContext<FooHub>().Returns(_hubContext); _mockClient = Substitute.For<IMockClient>(); SubstituteExtensions.Returns(_hubContext.Clients.All, _mockClient); } [Test] public void PushFooUpdateToHub_CallsUpdateFooOnHubClients() { var fooDto = new FooDto(); var hub = new FooHub(_connectionManager); hub.PushFooUpdateToHub(fooDto); _mockClient.Received().updateFoo(fooDto); } public interface IMockClient { void updateFoo(object val); } } public class FooHub : Hub { private readonly IConnectionManager _connectionManager; public FooHub(IConnectionManager connectionManager) { _connectionManager = connectionManager; } public void PushFooUpdateToHub(FooDto fooDto) { var context = _connectionManager.GetHubContext<FooHub>(); context.Clients.All.updateFoo(fooDto); } } 
+5
source

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


All Articles