c# - NSubstitute 模拟扩展方法

标签 c# random mocking nsubstitute

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

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

最佳答案

根据 Sriram 的评论,NSubstitute 不能模拟扩展方法,但您仍然可以将模拟参数传递给扩展方法。

在这种情况下,Random 类具有虚拟方法,因此我们可以直接使用 NSubstitute 和其他基于 DynamicProxy 的模拟工具模拟它。 (特别是对于 NSubstitute,我们需要非常小心模拟类。请阅读 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);
    }
}

关于c# - NSubstitute 模拟扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28693698/

相关文章:

r - 在 R 中循环一组数字生成命令

arrays - Julia 中随机输出的数组理解

java - Spring Boot - 模拟对外部 API 的 POST REST 请求

c# - 如何在 AspNetCore.Authentication.Abstractions 上模拟 AuthenticateAsync

c# - 如何在 Windows 8 应用程序中使用 xaml 矢量图像作为图像源

c# - Entity Framework 无法与 MySql 一起使用

c# - Try/Catch——我怎么知道在奇怪/复杂的情况下要捕捉什么?

python - 在 Python 中从字典中获取随机值

java - 模拟端点期望中的 Apache Camel : usage of ValueBuilder. ConvertTo

c# - IEnumerable<T> 到 IDictionary<U, IEnumerable<T>>