NSubstitute模拟扩展方法 [英] NSubstitute mock extension method

查看:94
本文介绍了NSubstitute模拟扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做模拟扩展方法,但是不起作用.如何才能做到这一点?

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 });
}

推荐答案

NSubstitute无法根据Sriram的注释模拟扩展方法,但是您仍然可以将模拟参数传递给扩展方法.

NSubstitute can not mock extension methods as per Sriram's comment, but you can still pass a mocked argument to an extension method.

在这种情况下,Random类具有虚拟方法,因此我们可以使用NSubstitute和其他基于DynamicProxy的模拟工具直接对其进行模拟. (特别是对于NSubstitute,我们需要非常小心的模拟类.请阅读 the文档.)

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.)

public static class RandomExtensions {
    public static IEnumerable<int> NextInt32s(this System.Random random, int neededValuesNumber, int minInclusive, int maxExclusive) { /* ... */ }
}
public class RandomExtensionsTests {
    [Test]
    public void Select()
    {
        const int min = 0, max = 10;
        var randomizer = Substitute.For<Random>();
        randomizer.Next(min, max).Returns(1, 2, 3);

        var result = randomizer.NextInt32s(3, 0, 10).ToArray();

        Assert.AreEqual(new[] {1, 2, 3}, result);
    }
}

这篇关于NSubstitute模拟扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆