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

StackOverflow https://stackoverflow.com/questions/12921983

  •  07-07-2021
  •  | 
  •  

Вопрос

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");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top