Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq: How to get to a parameter passed to a method of a mocked service

Tags:

c#

moq

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?

like image 331
Jan Avatar asked Jul 17 '10 00:07

Jan


People also ask

How do you call an original method in mock?

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.

What is callback in Moq?

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.

What can be mocked with Moq?

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.

What is .setup in mock?

Setup method is used to set expectations on the mock object For example: mock. Setup(foo => foo. DoSomething("ping")). Returns(true);


1 Answers

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))); 
like image 99
Gamlor Avatar answered Sep 22 '22 23:09

Gamlor