72

Let's say I want to use Moq to create a callback on a setter to store the set property in my own field for later use. (Contrived example - but it gets to the point of the question.) I could do something like this:

myMock.SetupSet(x => x.MyProperty).Callback(value => myLocalVariable = value);

And that works just fine. However, SetupSet is obsolete according to Intellisense. But it doesn't say what should be used as an alternative. I know that moq provides SetupProperty which will autowire the property with a backing field. But that is not what I'm looking for. I want to capture the set value into my own variable. How should I do this using non-obsolete methods?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
RationalGeek
  • 9,425
  • 11
  • 62
  • 90

1 Answers1

119

I am using Moq version 3.0.204.1 and SetupSet does is not marked as obsolete for me. However, there are a couple of SetupSet overloads located in MockLegacyExtensions. You can avoid using those and use SetupSet that is defined on the Mock class.

The difference is subtle and you need to use Action<T> as SetupSet parameter, as opposed to Func<T, TProperty>.

The call below will invoke the non-deprecated overload:

myMock.SetupSet(p => p.MyProperty = It.IsAny<string>()).Callback<string>(value => myLocalVariable = value);

The trick is to use It.IsAny<string>, which will intercept a setter call with any value.

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
Igor Zevaka
  • 74,528
  • 26
  • 112
  • 128
  • 3
    It's a shame that you need to specify the generic argument for `Callback<>` – RobSiklos Sep 06 '13 at 13:09
  • @RobSiklos What shame? In the [QuickStart](https://code.google.com/p/moq/wiki/QuickStart) it called _alternate equivalent generic method syntax_ – Yaro Sep 18 '13 at 21:02
  • 7
    @RobSiklos You can write `Callback((string value) => myLocalVariable = value)` – LazyTarget Oct 03 '14 at 07:26