I am new to MOQ and I have read the Quickstart here. I am using MOQ v4.2.1402.2112. I am trying to create a unit test for updating a person object. The UpdatePerson
method returns the updated person object. Can someone tell me how to correct this?
I am getting this error:
Moq.MockException was unhandled by user code
HResult=-2146233088
Message=Error updating Person object
Expected invocation on the mock once, but was 0 times: svc => svc.UpdatePerson(.expected)
Configured setups: svc => svc.UpdatePerson(It.IsAny<Person>()), Times.Never
No invocations performed.
Source=Moq
IsVerificationError=true
Here's my code:
[TestMethod]
public void UpdatePersonTest()
{
var expected = new Person()
{
PersonId = new Guid("some guid value"),
FirstName = "dev",
LastName = "test update",
UserName = "[email protected]",
Password = "password",
Salt = "6519",
Status = (int)StatusTypes.Active
};
PersonMock.Setup(svc => svc.UpdatePerson(It.IsAny<Person>()))
.Returns(expected)
.Verifiable();
var actual = PersonProxy.UpdatePerson(expected);
PersonMock.Verify(svc => svc.UpdatePerson(It.IsAny<Person>()), Times.Once(), "Error updating Person object");
Assert.AreEqual(expected, actual, "Not the same.");
}
With this line
PersonMock.Verify(svc => svc.UpdatePerson(It.IsAny<Person>()),
Times.Once(), // here
"Error updating Person object");
You are setting expectation on mock that UpdatePerson
method should be called once. It fails, because your SUT (class you are testing) does not call this method at all:
No invocations performed
Also verify if you pass mocked object to PersonProxy
. It should be something like:
PersonProxy = new PersonProxy(PersonMock.Object);
And implementation
public class PersonProxy
{
private IPersonService service; // assume you are mocking this interface
public PersonProxy(IPersonService service) // constructor injection
{
this.service = service;
}
public Person UpdatePerson(Person person)
{
return service.UpdatePerson(person);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With