简体   繁体   中英

Can't verify Moq method call

There is a problem with verifying TextWriter Write method call, with given params. I have this verification code:

_htmlHelperMock.TextWritterMock.Verify(x => x.Write(It.Is<IHtmlString>(p => p == MvcHtmlString.Create("</div>"))), Times.Once);

which throws this exception:

Expected invocation on the mock once, but was 0 times: x => x.Write(It.Is<IHtmlString>(p => p == MvcHtmlString.Create("</div>")))  
No setups configured.

Performed invocations:  
TextWriter.Write(<div class="control-group">)  
TextWriter.Write(</div>)

It is interesting that in exception I see the real invocation with strings I want to check. How should I configure verify method to check params?

When you are verifying with It.Is<IHtmlString>(p => p == MvcHtmlString.Create("</div>")) (without my understanding of MvcHtmlString , it's clear already this will fail). Whatever you invoked during the test will be a different object returned by Create . In this Verify it is comparing two instances with == . These will be object reference equality.

You probably want a Func<IHtmlString,bool> which compares the value, not the instance. Are you able to compare a p.ToString() (or ToHtmlString() ) to simply the string "</div>" ? The Create seems like extra work.

It.Is<T> takes a function that says "Given a recorded object of type T , verify something about that object". So, this expands to (conceptually):

IHtmlString actual = theRecordedParameter;
IHtmlString expected = MvcHtmlString.Create("</div>");
bool pass = actual == expected;
Assert.IsTrue(pass);

By using some intermediate operations, you can operate on two distinct objects actual and expected, and compare some derived values.

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