rom*_*ryn 9 c# random mocking nsubstitute
我想做模拟扩展方法,但它不起作用.如何才能做到这一点?
public static class RandomExtensions
{
public static IEnumerable<int> NextInt32s(this System.Random random, int neededValuesNumber, int minInclusive, int maxExclusive)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
[Fact]
public void Select()
{
var randomizer = Substitute.For<DefaultRandom>();
randomizer.NextInt32s(3, 1, 10).Returns(new int[] { 1, 2, 3 });
}
Run Code Online (Sandbox Code Playgroud)
根据 Sriram 的评论,NSubstitute 无法模拟扩展方法,但您仍然可以将模拟参数传递给扩展方法。
在这种情况下,该类Random具有虚拟方法,因此我们可以直接使用 NSubstitute 和其他基于 DynamicProxy 的模拟工具来模拟它。(特别是对于 NSubstitute,我们需要非常小心地模拟类。请阅读文档中的警告。)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11421 次 |
| 最近记录: |