Imagine this class
public class Foo { private Handler _h; public Foo(Handler h) { _h = h; } public void Bar(int i) { _h.AsyncHandle(CalcOn(i)); } private SomeResponse CalcOn(int i) { ...; } }
Mo(q)cking Handler in a test of Foo, how would I be able to check what Bar()
has passed to _h.AsyncHandle
?
Set CallBase to true on your mock. This will call the original virtual methods or properties if they exist, and haven't been set up to return a canned value.
Callbacks. A powerful capability of Moq is to attach custom code to configured methods and properties' getters and setters. This capability is often referred to as Callbacks.
Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.
Setup method is used to set expectations on the mock object For example: mock. Setup(foo => foo. DoSomething("ping")). Returns(true);
You can use the Mock.Callback-method:
var mock = new Mock<Handler>(); SomeResponse result = null; mock.Setup(h => h.AsyncHandle(It.IsAny<SomeResponse>())) .Callback<SomeResponse>(r => result = r); // do your test new Foo(mock.Object).Bar(22); Assert.NotNull(result);
If you only want to check something simple on the passed in argument, you also can do it directly:
mock.Setup(h => h.AsyncHandle(It.Is<SomeResponse>(response => response != null)));
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