I want to do mock extension method, but it does not work. How can this be done?
public static class RandomExtensions
{
public static IEnumerable<int> NextInt32s(this System.Random random, int neededValuesNumber, int minInclusive, int maxExclusive)
{
// ...
}
}
[Fact]
public void Select()
{
var randomizer = Substitute.For<DefaultRandom>();
randomizer.NextInt32s(3, 1, 10).Returns(new int[] { 1, 2, 3 });
}
According to SOLID principle dependence inversion defines that lower level model should not be depended high level model but depended on abstract like interface and mocking concept is mainly used to mock interface so that low level model is not tested.
NSubstitute can not mock extension methods as per Sriram's comment, but you can still pass a mocked argument to an extension method.
In this case, the
Random
class has virtual methods, so we can mock that directly with NSubstitute and other DynamicProxy-based mocking tools. (For NSubstitute in particular we need to be very careful mocking classes. Please read the warning in the documentation.)Yes you can mock if you create an interface such as
IRandom
and extend the interface instead of the actual implementation. Then you should be able mock the interface in your test class.In your test class add:
By this process you are just mocking the interface not the actual class.