raising/invoking events

B

Berryl Hesh

I am experimenting with a class of widgets, and trying to decide on a
general strategy for testing them. Say my button widget has a property in
it's interface of:
public event EventHandler Click;

If I implement this as a Win Forms button, I know I can use the implemented
buttons PreformClick() method to test it, but how can I do this more
generically, just using the .Net event? For example, in the sample test code
below, I think I want to do something like
widgetHello.Click.Invoke(this, EventArgs.Empty);
which doesn't even compile much less work.

Thanks for the help - BH


[Test]
public void ClickEvent_CanBeDelegated_ToAnArbitraryMethod() {
// arrange
Assert.That(HelloMessage, Is.EqualTo(null));
var btnHello = new Button {Text = "Click Me"};
var widgetHello = new WinButton(btnHello);
widgetHello.Click += delegate { SayHello(); };
// act
btnHello.PerformClick();
// assert
Assert.That(HelloMessage, Is.EqualTo("Hello World"));
}
 
M

Marc Gravell

There isn't a safe way of raising an arbitrary event. In this case,
one option might be to add an "internal" method that raises the event
- for example (extending the typical protected virtual OnFoo method):

public event EventHandler Foo;
protected internal virtual void OnFoo() {
if(Foo!=null) Foo(this,EventArgs.Empty);
}

then use the [InternalsVisibleTo] attribute to allow your test project
access to the internal method. Your test project can now call OnFoo()
to raise the event.

This only works if you own the type, of course.

Marc
 
B

Berryl Hesh

I'd like to be able to test Foo != null, and I don't understand the logic of
"Click' can only appear on the left hand side of += or -. Iis there another
way to determiine if an event is null from another class?

Thanks for sharing! BH


public event EventHandler Click;
protected internal virtual void OnClick() {
if(Click!=null) Foo(this,EventArgs.Empty);
}
 
B

Berryl Hesh

I understand the encapsulation side, ie, invoking the event. It's the
testing of whether its subscribed to that I don't grok.

What I want to do here is be able to trigger an event, in a test, so I know
it is doing what it should, especially after refactoring something. I also
like to test that the event has been subscribed to in test code (less
useful). I know I can provide hooks to do these things from the owning
class, but then I have broken encapsulation to do so.

Can you recommend a test framework for this?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top