-
-
Notifications
You must be signed in to change notification settings - Fork 802
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Raise event when stubbed property is changed #745
Comments
I want the event to be fired automatically when a stubbed property is changed but it seems that this functionality is missing. |
@yordans - It appears that you've already answered your own question for the most part: public interface IFoo
{
int Foo { get; set; }
event EventHandler FooChanged;
}
var mock = new Mock<IFoo>();
mock.Object.FooChanged += (s, e) => Console.WriteLine("Foo property changed.");
mock.SetupSet(m => m.Foo = It.IsAny<int>()).Raises(m => m.FooChanged += null, EventArgs.Empty);
mock.Object.Foo = 5; The above will fire the event whenever the property is set, not when it is changed. If you want the latter, you'll need something more elaborate: int value = default(int); // this will act as the "backing field" for the property
mock.SetupGet(m => m.Foo).Returns(() => value);
mock.SetupSet(m => m.Foo = It.IsAny<int>()).Callback((int newValue) =>
{
bool shouldRaiseChangedEvent = newValue != value;
value = newValue;
if (shouldRaiseChangedEvent)
{
mock.Raise(m => m.FooChanged += null, EventArgs.Empty);
}
}); Not so different from how you'd implement If you want an API that creates such a setup for any pair of a property Does this answer your question? |
It is fine the event to be fired when the property is set, but the real problem is that I want the mock to "track" sets/gets to this property (i.e. Stub) + firing event.
won't track the property Foo. |
What exactly do you mean by "tracking a property"?
Did you notice the second part of my above post? Because that's exactly what it does. |
When setup property in this way: And the question is could this kind of stubbed property be setup to raise an event when changed? |
I'll once again refer you to my first post above which shows you just how to do that. (And no, |
Thank you for your responses. I think the issue can be closed. Is it planned |
No, such an extension isn't planned at the moment. |
@stakx When implementing what you describe here I ran in to the problem that |
@jhv2017kam, no, that helper method definitely does not belong in Moq's public API... it's strictly an implementation detail. But it should be easy enough to replicate in your own code. |
How to raise event when stubbed property (automatically tracking its value) is changed (setter called)?
e.g.
mock.SetupProperty(m => m.Foo).Raises(m => m.FooChanged += null);
mock.Object.Foo = 5; // raises the FooChanged event on ISomething
The text was updated successfully, but these errors were encountered: