tenpn
tenpn

Reputation: 4716

Using the current object instance in a Moq callback

I want to create a stub using Moq that has a function Foo that will push the stub instance onto a list passed as a parameter. I can use the Callback<>() method to capture the list, but I don't have access to the stub instance from there, do I?

This is what I've got so far:

var stubPattern = new Mock<IBar>();
stubPattern.Setup(stub => stub.Foo(It.IsAny<List<IBar>>()))
    .Callback<List<IBar>>(list => list.Add(stubInstance); // stubInstance not valid

Is it possible to do something like this in Moq?

Upvotes: 2

Views: 880

Answers (1)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

If you mean to get the mock instance itself, you can use Object property.

stubPattern.Setup(stub => stub.Foo(It.IsAny<List<IBar>>()))
           .Callback<List<IBar>>(list => list.Add(stubPattern.Object);

Upvotes: 5

Related Questions