Search code examples
c#.netunit-testingnunitxsockets.net

Create Unit test for Xsockets


I'm trying to better understand how to use unit tests. I want to test Send and Receive in Xsockets with Nunit.

Right now when I run the test nothing is happening

I just want to create the listener and then call invoke, then wait and update the result value.

I want something like when you test an event Unit testing that an event is raised in C#

Xsockets C#

[Test]
public  void Xsockets_Change_Test()
{
    var mocks = new MockRepository();
    var metaData = mocks.CreateMock<MetaData>();
    var result = 0;

    controller.On<MetaData>("Change",
        (message) =>
        {
            result++;
        });

    controller.Invoke("Change", metaData);            
    Assert.That(result, Is.EqualTo(1));
}

IListener On<T>(string target, Action<T> action);

void Invoke(string target, object data);

Solution

  • You should show in your code sample exactly what controller is and where it comes from, but looking at the XSockets link you provide I think I know what you are expecting.

    The problem you are having is a common one when testing with threads, sockets, or any scenario where there is a continuity break in code execution. The solution is to either remove the discontinuity or account for it.

    The problem lies in the fact that you don't know exactly when the event will be processed. In most cases (every case?) your assertion will be executed before the event handler and the test will fail.

    In effect here you are testing both the XSocket functionality and your code. I have found that most times you do not want to test the XSocket library (at least not here - this is a unit test for your code). In this case you want to remove the XSocket code from the test. To do this you can mock (or stub) the controller to invoke your event code directly.

    The other possibility is to account for the discontinuity by waiting for the result value to change for some (probably short) period of time and failing the test only if the change does not happen in the allotted time. I wouldn't usually recommend this approach, but it is justified occasionally if there is the desire to test the code with the socket functionality in place.