I have a in issue where I would like to swap out Moq for NSubstitute entirely. In most cases, this is extremely straightforward, however I have run across a fairly specialized issue.
Here's the Moq code.
_registrationCommandHandler.Setup(c => c.Execute
(It.Is<CheckUniqueUserCommand>(r => r.Request.UserName == "fred"))).
Callback((CheckUniqueUserCommand c) =>
{
c.Response = new CheckUserNameIsUniqueResponse()
{
IsUnique = true,
Success = true
};
c.Success = true;
});
The closest I seem to be able to get with NSubstitute is
_registrationCommandHandler.When(c => c.Execute
(Arg.Any<CheckUniqueUserCommand>())).Do
((CheckUniqueUserCommand c) =>
{
c.Response = new __Internal.CheckUserNameIsUniqueResponse()
{
IsUnique = true,
Success = true
};
c.Success = true;
});
which won't even compile. This leaves me a bit stuck. Does anyone have any suggestions?
I'm guessing a bit here, but try:
_registrationCommandHandler
.When(c => c.Execute(Arg.Is<CheckUniqueUserCommand>(r => r.Request.UserName == "fred")))
.Do(call => {
var c = call.Arg<CheckUniqueUserCommand>();
c.Response = new __Internal.CheckUserNameIsUniqueResponse()
{
IsUnique = true,
Success = true
};
c.Success = true;
});
NSubstitute does not do the same argument passing as Moq does for callbacks. Instead it passes a parameter with information about the call, and you can access the arguments using call.Arg<T>
or call[i]
.
In addition to changing the .Do
block, I also switched from using Arg.Any(..)
to Arg.Is(..)
to closer match the Moq sample.
Hope this helps.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments