我有一个定义为
的界面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,以便如果upperVal低于lowerVal,则抛出异常
mock.Object.AddNumbersBetween(4,1);//should throw an exception
基本上寻找类似的东西:
mock.Setup(foo => foo.AddNumbersBetween("arg1 is higher than arg2")).Throws<ArgumentException>();
答案 0 :(得分:95)
我知道这已经有一年了,但我找到了一种方法,可以使用最新版Moq的多个参数:
mock.Setup(x => x.Method(It.IsAny<int>(), It.IsAny<int>()))
.Returns<int, int>((a, b) => a < b);
答案 1 :(得分:9)
对于单参数方法,最简洁的方法是:
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;
}