This is a migrated thread and some comments may be shown as answers.

How can I check, if a method is called after raising an event.

0 Answers 36 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Bernhard
Top achievements
Rank 1
Bernhard asked on 01 Oct 2012, 01:06 PM
Hello all,

I try to test if controller object has assigned a method to an event (see sample code at the end). 

I have a controller object, which gets two objects (getCalled & raiseEvent) via an interface. The object getCalled provides a 
method which should be assigned to an event of the object raiseEvent. This should be preformed from within the controller object.
The event can only occur after the raiseEvent.Start method has been called.

I thought, I write an Arrange statement, where the method getCalled.callMe must be called.
Additionally I write an Arrange statement, where an event should be raised, when the raiseEvent.Start method gets called.
Now I create the controller and call the method controller.Start. In this method the the method raiseEvent.Start will be called, which should rasie the Event raiseEvent.calledEvent, which should call the method getCalled.CallMe.
But the testrunner asserts with the message
"Setup contains calls that are marked as "MustBeCalled" but actually never called"

What do I make wrong?

best regards
  Bernhard

Here is the sample code

    using NUnit.Framework;

    using Telerik.JustMock;
    using Telerik.JustMock.Helpers;

    public interface IGetCalled
    {
        void CallMe(EventArgs arg);
    }

    public interface IRaiseEvent
    {
         event EventHandler<EventArgs> calledEvent;
         void Start();
    }

    public class Controller
    {
         private IRaiseEvent raiseEvent;
         private IGetCalled  getCalled;

         public Controller(IGetCalled getCalled, IRaiseEvent raiseEvent)
         {
             this.raiseEvent = raiseEvent;
             this.getCalled  = getCalled; 
     
             this.raiseEvent.calledEvent += (s, e) => this.getCalled.CallMe(e);         
         }
                        
         public void Start()
         {
             raiseEvent.Start();   
         }
    }

    [TestFixture]
    public class test
    {
        [Test]
        public void TestRaiseEvent()
        {
            IRaiseEvent raiseEvent = Mock.Create<IRaiseEvent>();
            IGetCalled getCalled = Mock.Create<IGetCalled>();

            getCalled.Arrange(x => x.CallMe(new EventArgs())).MustBeCalled();
            Mock.Arrange(() => raiseEvent.Start()).Raises(() => raiseEvent.calledEvent += null, new EventArgs());
            var controller = new Controller(getCalled, raiseEvent);

            controller.Start();
            getCalled.Assert();
        }
    }

No answers yet. Maybe you can help?

Tags
General Discussions
Asked by
Bernhard
Top achievements
Rank 1
Share this question
or