Setup multiple results based on given args, plus an additional case to fallback invocations

187 views
Skip to first unread message

amiralles

unread,
Apr 26, 2013, 1:40:46 PM4/26/13
to moq...@googlegroups.com
Hi guys i have this code,
public class Demo {
        public interface IFoo {
            int Bar(string arg);
        }
 
        [Test]
        public void TestFoo() {
            var foo = new Mock<IFoo>();
            foo.Setup(f => f.Bar("aaa")).Returns(1);
            foo.Setup(f => f.Bar("bbb")).Returns(2);
            //
            foo.Setup(f => f.Bar(It.IsAny<string>())).Returns(3);
            //instead of the previous line, I would go with something like this:
            //foo.Setup(f => f.Bar(It.IsAnyOther<string>())).Returns(3);
 
            //With the current setup, these first two asserts are gonna fail,
            //because It.IsAny<string>() is going to match for any string argument....
            Assert.AreEqual(1, foo.Object.Bar("aaa"));
            Assert.AreEqual(2, foo.Object.Bar("bbb"));
            Assert.AreEqual(3, foo.Object.Bar("ccc"));
        }
    }

What I want, is to provide a default result for any invocation that does not match against the specified setup.
I know if I remove It.IsAny<string>  I'll get the default value of the method's return type, which in the sample above will be 0, but I want to be 3.
Is there any hack or known workaround to do that?
Thanks!

Daniel Cazzulino

unread,
Apr 26, 2013, 2:21:43 PM4/26/13
to moqdisc
Set the more generic setup first. The other two will override it afterwards.


/kzu

--
Daniel Cazzulino


--
--
Post: moq...@googlegroups.com
Unsubscribe: moqdisc-u...@googlegroups.com
---
You received this message because you are subscribed to the Google Groups "Moq Discussions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to moqdisc+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

mari...@gmail.com

unread,
Apr 26, 2013, 2:21:05 PM4/26/13
to moq...@googlegroups.com
Change the order of the setups definition to:
 
  foo.Setup(f => f.Bar(It.IsAny<string>())).Returns(3);
  foo.Setup(f => f.Bar("aaa")).Returns(1);
  foo.Setup(f => f.Bar("bbb")).Returns(2);
 
If that does not work you can use It.Is matcher instead:
 
foo.Setup(f => f.Bar(It.Is(a => a != “aaa” && a != “bbb”)>())).Returns(3);
 
Regards
 
--

Ale Miralles

unread,
Apr 26, 2013, 2:54:57 PM4/26/13
to moq...@googlegroups.com

Thanks, worked like  a charm!

Reply all
Reply to author
Forward
0 new messages