How do I verify a method was called exactly once with Moq? The Verify()
vs. Verifable()
thing is really confusing.
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
You can use
Times.Once()
, orTimes.Exactly(1)
:Here are the methods on the Times class:
AtLeast
- Specifies that a mocked method should be invoked times times as minimum.AtLeastOnce
- Specifies that a mocked method should be invoked one time as minimum.AtMost
- Specifies that a mocked method should be invoked times time as maximum.AtMostOnce
- Specifies that a mocked method should be invoked one time as maximum.Between
- Specifies that a mocked method should be invoked between from and to times.Exactly
- Specifies that a mocked method should be invoked exactly times times.Never
- Specifies that a mocked method should not be invoked.Once
- Specifies that a mocked method should be invoked exactly one time.Just remember that they are method calls; I kept getting tripped up, thinking they were properties and forgetting the parentheses.
Imagine we have are building a calculator with one method for adding 2 integers. Let's further imagine the requirement is that when the add method is called, it calls the print method once. Here is how we would test this:
And here is the actual test with comments within the code for further clarification:
Test controller may be :
And When DeleteCars method called with valid id, then we can verify that, Service remove method called exactly once by this test :