Mocking General Method with NSubstitute

I have an interface with a number of common methods. These methods perform operations based on the type of data that is transmitted. How can I do this with NSubstitute? At the moment, I had to resort to using a specific class instead of a layout, since I can not handle all the possible types with which the method will be called.

public interface IInstanceSource { bool CanCreate<T>(); T Create<T>(); void Register<T>(Func<T> creator); } public static IInstanceSource GetInstanceSource() { var _data = new Dictionary<Type, Func<object>>(); var a = Substitute.For<IInstanceSource>(); //code below fails since T is not defined. How do I make the code below accept any type? a.WhenForAnyArgs(x=>x.Register(Arg.Any<Func<T>>)).Do(x=> { /* todo */}); a.CanCreate<T>().Returns(x => _data[typeof (T)]); return a; } 

thanks.

+4
source share
1 answer

NSubstitute does not support automatic configuration of multiple instances of a common method.

As we usually see, the IInstanceSource used in the test is to configure it for specific code of the tested code, so T will be known. If one tool should work for several different T s, we could simplify the configuration using a helper method, for example ConfigureInstanceSource<T>() , which will perform configuration steps for a specific T

In your case, although it seems that you want a fixed behavior for all fake IInstanceSource instances, in which case I believe that you did the right thing by manually encoding your own double test.

+4
source

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


All Articles