chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
I have class
public class SomeClass
    public EventHandler SomeEvent;

I only know what SomeClass have event.

For example, after create SomeClass SomeEvent should "fire" 3 times.
How i can test what SomeEvent has fire.
public class MyClass
    private SomeClass _myObject = new SomeClass();
    public MyClass()
        _myObject.SomeEvent += mySomeEvent;

    private void mySomeEvent(SomeClass m, EventArgs e)
        System.Diagnostics.Trace.WriteLine("Main tick message");


If this SomeClass using in another Class i try next code for test.
[TestMethod, Isolated]
public void TestMethod1()
    SomeClass fakeSomeClass = Isolate.Fake.Instance<SomeClass>(Members.CallOriginal);
    fakeSomeClass.SomeEvent += fakeSomeEvent;  
    MyClass d = new MyClass();

private void fakeSomeEvent(SomeClass m, EventArgs e)
    System.Diagnostics.Trace.WriteLine("Fake tick message");


But always fire method mySomeEvent from MyClass, i wait fire method fakeSomeEvent from test.
Sorry for my English.
asked by yus (600 points)

1 Answer

+1 vote

Hi yus,


Instead of faking the event you can fake the callback method.

public class SomeClass

        public EventHandler SomeEvent;
    public class MyClass
        private SomeClass _myObject = new SomeClass();
        public MyClass()
            _myObject.SomeEvent += mySomeEvent;
        //this simulates the fire event for the example
        public void SomethingThatInvokesTheEvent()
        private void mySomeEvent(object m, EventArgs e)
            System.Diagnostics.Trace.WriteLine("Main tick message");


This is the test method:

We added wasCalled field in order for the assert 

        public void TestMethod1()
            bool wasCalled = false;
            var myClass = new MyClass();
            Isolate.NonPublic.WhenCalled(myClass, "mySomeEvent"nullnull).DoInstead(c => wasC            alled = true);


We added a method that fires the event(SomethingThatInvokesTheEvent()),

So you can fire the event from the test after you fake the event.

Is this what you needed?
answered by Bar (3.3k points)