简体   繁体   中英

Is a call needed to Setup a method on Mock object that we want to Verify that it is called using Moq?

I have a unit test that should Verify that a specific method is called when calling sut.ProcessCommand .

Is there any benefit of Setting up that method even though I Verify that it is called in my unit test. And that method to be verified doesn't return any value and it is the last method to be called in MethodA

Unit Test with Setting up the method

 [TestMethod]
 Public void VerifyMethodACalled()
 { 
   Mock<ISomeInterfacce> mockObject=new Mock<ISomeInterface>();
   mockObject.Setup(mockObj=> mockObj.MethodA(It.Is<ClassA>(classAObj=>classAObj.Name="SomeName")));

   //Act
   sut.ProcessCommand();

   mockObject.Verify(mockObj=> mockObj.MethodA(It.Is<ClassA>(classAObj=>classAObj.Name="SomeName")), Times.Once);

 }

Unit Test without Setting up the method

 [TestMethod]
 Public void VerifyMethodACalled()
 { 
   Mock<ISomeInterfacce> mockObject=new Mock<ISomeInterface>();

   //Act
   sut.ProcessCommand();

   mockObject.Verify(mockObj=> mockObj.MethodA(It.Is<ClassA>(classAObj=>classAObj.Name="SomeName")), Times.Once);

 }

In the example, you provided there is absolutely no difference since you verify the method against the invocation list in both cases.


Effectively moq internally maintains the list of setup methods and the list of the invocations. You could verify the method against the invocation list but you can also verify the setup itself. What does that mean? You can think of that verifying against the invocation list, the example you provided, is actually some kind of deferred verification. Let's look at the example (maybe it is not realistic but depicts what I am trying to explain)

public class MyData
{
    public string Id { get; set; }
}

public interface IMyInterface
{
    int MyMethod(MyData data);
}

Verify against the invocation list

var p = new Mock<IMyInterface>();
var myData = new MyData {Id = "1"};
p.Object.MyMethod(myData);
myData.Id = "2";
p.Verify(m => m.MyMethod(It.Is<MyData>(d => d.Id == "1"))); //this will fail

Verify against the setup

var p = new Mock<IMyInterface>();
p.Setup(m => m.MyMethod(It.Is<MyData>(d => d.Id == "1"))).Verifiable();
var myData = new MyData {Id = "1"};
p.Object.MyMethod(myData);
myData.Id = "2";
p.Verify(); //this won't fail

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