Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple parameters call back in Moq

Tags:

callback

moq

Can someone please look at the code below and see what's wrong?

[TestInitialize]
public void SetupMockRepository()
{
    var memberId = "34345235435354545345";
    var title = "test";
    var url = "dafdsfdsfdsfdsafd";

    _mockPropertySearchRepository = new Mock<IPropertySearchRepository>(MockBehavior.Strict);
    _mockPropertySearchRepository
        .Setup(p => p.SaveSearchURL(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
            .Callback<string,string,string>((id,t,u) =>  )
            .Returns(new SavedSearchReturnResult() );

}

Thanks

like image 472
user2388013 Avatar asked Sep 05 '13 04:09

user2388013


People also ask

What is callback in Moq?

A callback is a piece of code that is passed into to a method parameter to be executed from within that method. Callbacks allow you to extend the functionality of such methods. When using Moq to create test doubles, you can supply callback code that is executed when an expectation is met.

What is verifiable in Moq?

Verifiable is to enlist a Setup into a set of "deferred Verify(...) calls" which can then be triggered via mock. Verify() .


2 Answers

I managed to solve the problem myself as below

[TestInitialize]
public void SetupMockRepository()
{
    var memberId = "34345235435354545345";
    var title = "test";
    var url = "dafdsfdsfdsfdsafd";


    _mockPropertySearchRepository = new Mock<IPropertySearchRepository>(MockBehavior.Strict);
    _mockPropertySearchRepository
        .Setup(p => p.SaveSearchURL(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
        .Callback<string,string,string>(
            (id, t, u) =>
            {
                memberId = id;
                title = t;
                url = u;
            })
        .Returns(new SavedSearchReturnResult());
}
like image 51
user2388013 Avatar answered Oct 17 '22 19:10

user2388013


For each parameter that the method takes, pass a type parameter to the Callback method.

someMock
    .Protected()
    .Setup("SomeMethod", ItExpr.IsAny<string>(), ItExpr.IsAny<string>())
    .Callback<string, string>((x, y) => {});

The above works both with Protected and normal callbacks.

like image 36
Shaun Luttin Avatar answered Oct 17 '22 20:10

Shaun Luttin