samedi 27 juin 2015

TDD Testing service/background code in C#

So, I'm coding a little async server that would call a delegate each time it receives a message from the network, and I'm having trouble in how to test the class. I'm new to testing, I've done my first tests using TDD in JavaScript and now I'm trying to do TDD C#.

I've started by writing my first test and I imagined I'd like some static factory for constructing the object, so that if parameters aren't valid or null, I could check them before constructing the object, so I wrote this, and did the fist cycle of red-green-refactor.

[TestMethod]
public void CreateShouldCreateAnInstanceWithValidParameters()
{
    MessageReceivedCallback callback = delegate(Message message, TcpClient sender) {};
    AsyncTcpServer server = AsyncTcpServer.Create(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 40400), callback);
    Assert.IsTrue(server != null && server is AsyncTcpServer);
}

I think its good so far (afaik).

Now, I think I need some Start() and Stop() methods to launch this server in the background, so they would be synchronous methods which the first launches a thread for some code that would read from the TcpListener until I call Stop().

Now here is the problem, because lots of questions arise and I don't seem to find the best solution (or just a solution) for the problems:

  • What do I test the Start() method for? Do I check that it creates a thread? Or would it be a better idea to provide the status of the server, in the form of some property like IsRunning and make sure that before Start() is called its false, after Start() is true, and then after Stop() is false?

  • And in case I test for the IsRunning value, would it be a little bit fake if, I make it pass with just implementing the code necessary (as said in several books and tutorials to only implement the code necessary to make the test pass) for the value to change after the calls are made, without creating the thread? I think that if I create the Thread, it would be untested code, since I can't find a proper way to test if the thread was created (I could expose the thread member of the class as public, but I think that would be ugly and not a very encapsulated class).

So, what am I doing wrong? What should I do?

Aucun commentaire:

Enregistrer un commentaire