建立一个基于参数值(多个参数)的方法

我有一个接口定义为

interface IMath
{
AddNumbersBetween(int lowerVal, int upperVal);
}

我可以为以上内容设置一个基本的 Moq:

Mock<IMath> mock = new Mock<IMath>();
mock.Setup(m => m.AddNumbersBetween(It.IsAny<int>(), It.IsAny<int>()));

宣布死亡

mock.Object.AddNumbersBetween(1,4);

然后验证它是否被调用

mock.Verify(m => m.AddNumbersBetween(1,4), Times.AtleastOnce());

我不知道如何设置方法 AddNumbersbetween,如果上面的 Val 小于下面的 Val,就会抛出异常

mock.Object.AddNumbersBetween(4,1);//should throw an exception

基本上就是在寻找这样的东西:

mock.Setup(foo => foo.AddNumbersBetween("arg1 is higher than arg2")).Throws<ArgumentException>();
99971 次浏览

对于单参数方法,最简洁的方法是:

mock.Setup(foo => foo.Submit(IsLarge())).Throws<ArgumentException>();
...
public string IsLarge()
{
return Match<string>.Create(s => !String.IsNullOrEmpty(s) && s.Length > 100);
}

如果该方法有多个参数,则不能应用此方法。仍然有一个“变通方案”可以使用,它模仿你想要实现的目标:

/// <summary>
/// Tests if a moq can send an exception with argument checking
///</summary>
[TestMethod]
public void TestException()
{
Mock<IMath> mock = new Mock<IMath>();
mock.Setup(m => m.AddNumbersBetween(It.IsAny<int>(), It.IsAny<int>()));


mock.Setup(foo => foo.AddNumbersBetween(It.IsAny<int>(), It.IsAny<int>()))
.Callback<int, int>((i, j) => CheckArgs(i, j));


try
{
mock.Object.AddNumbersBetween(1, 2);
}
catch (Exception ex)
{
// Will not enter
Console.WriteLine("Exception raised: {0}", ex);
}
try
{
mock.Object.AddNumbersBetween(2, 1);
}
catch (Exception ex)
{
// Will enter here, exception raised
Console.WriteLine("Exception raised: {0}", ex);
}
}


private bool CheckArgs(int i, int j)
{
if( i > j)
throw new ArgumentException();
return true;
}

I know this is a year old, but I found a way to use multiple parameters with the latest version of Moq at least:

mock.Setup(x => x.Method(It.IsAny<int>(), It.IsAny<int>()))
.Returns<int, int>((a, b) => a < b);