简体   繁体   中英

Moq converts It.IsAny<Exception> to It.IsAny<string> in expectation

I'm using Moq for unit tests, and I've set up an expectation like this:

myMock.Expect(w => w.MyMethod(It.IsAny<string>(),
                              It.IsAny<string>(),
                              It.IsAny<string>(),
                              It.IsAny<System.Exception>(), null))
      .Returns(myResult);

the method it is mocking is:

logger.WriteLogItem(string1, string2, string3, System.Exception, IEnumerableInstantiation);

This builds and runs fine, however VerifyAll() does not pass, and the error I get is:

Moq.MockVerificationException : The following expectations were not met:
IMyClass l => l.MyMethod(It.IsAny<string>(), It.IsAny<string>(), 
                         It.IsAny<string>(), It.IsAny<String>(), null)

So it's changing the Exception to a string for some reason....

Has anyone seen this before/ have any idea why it's doing this and what I can do to fix it/work around it?

thanks!

Ah, it was a rookie error! And the conversion thing was just a red-herring designed to send me chasing round the internet looking for crazy answers that aren't out there.

I wasn't passing the myMock.Object through to the calling command!

Okay, so I created a test method that had an exception as a parameter and called that using moq in the way above, and it worked fine. So it doesn't seem to be a problem with passing an Exception as a parameter per se.

I also changed the first parameter from an enum value to an It.IsAny enum. So from

myMock.Expect(w =>
    w.MyMethod(**MyEnum.Value**,
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<System.Exception>(),
        null))
.Returns(myResult);

to

myMock.Expect(w =>
    w.MyMethod(**It.IsAny<MyEnum>()**,        
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<System.Exception>(),
        null))
.Returns(myResult);

and the output I got was:

IMyClass l =>
    l.MyMethod(IsAny<MyEnum>(),
        IsAny<MyEnum>(), 
        IsAny<MyEnum>(),
        IsAny<MyEnum>(),
        null)

So it looks like it's taking the type of the first parameter and applying it to all the rest for some reason.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM