我想做模拟扩展方法,但它不起作用。如何才能做到这一点?
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/