I’m trying to add a unit test to an authentication class I have. So, basically what it does is I call Login and I expect that it will return true and as a side effect will add a cookie.
Here is my unit test so far:
var mock=new Mock<IServerContext>(); //AddCookie method is within IServerContext
FSCAuth.Config.Server=mock; //set authentication to use mocked interface
mock.Setup(x=>x.AddCookie(new HttpCookie().Name=="??")); //question here
FSCAuth.Login("foo", "bar", false);
mock.VerifyAll();
My question is how can I check the argument passed into AddCookie? Basically, all I want to do is something like
bool AddCookieVerify(HttpCookie cookie)
{
return cookie.Name=="foobar"
}
and if my verify function returns false, then throw an error. I don’t understand how to express this operation though in Moq.
How do I do this?
Moq includes the
Itstatic class to let you specify what types of arguments you’re expecting. For instance, instead of your placeholder lineyou can do
And then it will fail verification unless it’s passed a value that satisfies that expression.
Also, you might think about switching from
Setup()followed byVerifyAll()to something that simply usesVerify()after the fact, such as:This avoids the need for you to explicitly set up your expectations in advance, and gets it down to one extra line of code.