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
Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!
0 votes
public void AddHttpListener(IHttpListener httpListener)
{
            if (httpListener.IsStarted)
                throw new Exception();
            _HttpListeners.Add(httpListener);
            httpListener.RequestReceived += OnRequestReceived;
}

void OnRequestReceived(object sender, RequestEventArgs e)
{
            try
            {
                _RouteCollection.Route(e.HttpContext);
            }
            catch (Exception ex)
            {
                SDKCommon.Logger.Log("HttpServer OnRequestReceived: " + ex.Message);
            }
}

Above is the eventhandler , I need
1. Could i know the eventhandler is correctly assigned??
2. When i use Isolate.Invoke.Event(()=>myFakeListener.RequestReceived+=null) , could i use verify to assure that
OnRequestReceived is invoked ??
asked by (12.1k points)

1 Answer

0 votes
Hi,

The example below should answer both questions:

The Code Under Test:

public class Foo
{

    public void AddHttpListener(HTTPListener httpListener)
    {    
        httpListener.RequestReceived += OnRequestReceived;
    }

    public void OnRequestReceived(object sender, EventArgs e)
    {
        //some logic
    }
}

public class HTTPListener
{
    public event EventHandler RequestReceived;
}


And the test code:
[TestMethod , Isolated]
public void TestMethod1()
{

    //ARRANGE
    var foo = Isolate.Fake.Instance<Foo>(Members.CallOriginal);
    var httpListener = new HTTPListener();

    //ACT
    foo.AddHttpListener(httpListener);
    Isolate.Invoke.Event(() => httpListener.RequestReceived += null, null, EventArgs.Empty);

    //ASSERT
    Isolate.Verify.WasCalledWithAnyArguments(() => foo.OnRequestReceived(null, null));
}


You can tell that the eventhandler is correctly assigned because the invokation of the event triggered it (Isolate.Verify) shows that.

2 things to know about the test above:
1) The test should be [Isolated] so the invokation would work.
2) You can use verify only on fake objects, thats why I faked Foo with call original.

Please let me know if it helps.
answered by (18k points)
...