MOQ - setting up a method based on argument values (multiple arguments)

Raj Rao picture Raj Rao · Nov 2, 2010 · Viewed 69.2k times · Source

I have an interface defined as

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

I can setup a basic Moq for the above as follows:

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

call it

mock.Object.AddNumbersBetween(1,4);

and then verify that it was called

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

I cant figure out how to setup the method AddNumbersBetween such that if the upperVal is lower than the lowerVal an exception is thrown

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

Essentially looking for something like:

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

Answer

Gustyn picture Gustyn · Dec 1, 2011

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