How do I raise an event in FakeItEasy for an event based on a custom delegate?
Asked Answered
P

2

6

The application I am testing is full of events based on custom delegates, such as this:

public delegate void NameChangedHandler(string name);
public event NameChanged OnNameChanged;
...
public void ChangeYourName(string newName)
{
    if( NameChanged != null )
        NameChanged(newName);
}

I want to mock out the class producing these events and raise these events to the class under test.

I know that FakeItEasy can use Raise.With() for raising events with the traditional event signatures of MyHandler(object sender, EventArgs e) or MyHandler(EventArgs e), but I don't know what to do in my situation.

Any ideas?

Postnasal answered 16/10, 2012 at 19:20 Comment(3)
I have run into the exact same thing just today. Can someone help here?Gabionade
I believe the answer is that FakeItEasy cannot do this. My solution was to refactor my event to take EventArgs.Postnasal
There is an issue raised for this github.com/FakeItEasy/FakeItEasy/issues/30Winola
D
3

As of FakeItEasy 2.0.0, this is now possible.

The Raising Events documentation topic has the full story, but the gist is that you'd use

fake.OnNameChanged += Raise.With<NameChanged>(newName);

As always, the event must be virtual.

Devaughn answered 27/5, 2016 at 20:39 Comment(0)
C
0

You could always make ChangeYourName virtual and replace the method.

A.CallsTo(()=>fakeClass.ChangeyourName(A<string>._)).Invokes((x)=>invokeMockEvent(x));

If that isn't what you wanted, I suppose if ChangeYourName is public you could just create your fake class

var class = new Class();
class.OnNameChanged += (x)=>
{
    Assert.AreEqual(x,"tim");
};

class.ChangeYourName("tim");
Coolish answered 12/8, 2013 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.