简体   繁体   中英

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

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?

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM