1

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 first 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?

1 Answer 1

2

Assuming you're trying to follow TDD, as you start writing your tests and code to satisfy them, your design may evolve. You'll find that something is hard to write a test for. This might happen because it's just a really hard thing to test, or it can be an indication that your trying to do too much.

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

The point of writing the minimum amount possible to make the test pass, is to ensure that you don't write code that you're not testing. This helps encourage you to refactor the code to improve the testability of your design in order to be able to write tests to get the code to do what you want it to.

Looking at your current situation, it feels like you're trying to put too much into your AsyncTcpServer class. From what I can tell, it's going to be responsible for several things including, managing a TCP connection and running a separate thread of execution. These are two distinct concerns, and by trying to test them both in the same class you're making life hard for yourself.

You need to try to separate the concerns and test them in isolation. So, for example, using you might create a ThreadedRunner something like this:

class ThreadedRunner {
    public ThreadedRunner(IRunnable runnable) {
      // store runnable
    }
    public void Start() {
      // start thread to execute runnable.ThreadFunction
    }
    public void Stop() {
      // Send stop message, block until done
    }
}

For the interface IRunnable:

interface IRunnable {
    void ThreadFunction();
    void Stop();
}

You can then test the ThreadedRunner using a test implementation of IRunnable. There would be other tests on the way, but eventually you might end up with something like:

class TestableRunnable : IRunnable {
    public bool IsRunning {get;set;}
    public void ThreadFunction() {
        // Sleep
        // IsRunning=true
        // WaitOnShutdownMutex
        // IsRunning=false
    }
    public void Stop() {
       // Set shutdown mutex
    }
}


TestRunnableStartsThreadAndStops() {
    // Create Testable... Pass it to Runner
    // Validate testable isn't running
    // tell runner to start, 
    // Validate testable isn't running (it should be sleeping if it's in another thread)
    // sleep to give it time to start thread
    // validate it's running
    // call stop
    // validate that it blocked until after the state is stopped
}

You can then move on to write a runnable to do with your thread handling section (it may be that all it does is delegate different elements of that process out to other classes, which in turn will have smaller sections of functionality, which you can test).

One of the key aspects of TDD is that it gets you to look at your code from a client and test perspective to try to encourage you to make your classes usable and testable through the process of refactoring.

3
  • So, that way the user would have to instantiate each component to have the server, from the ThreadedRunner to the implementation of the IRunnable, wouldn't he?. I'd like the user to only know one class that sets up the whole thing, like the AsyncTcpServer, but not holding the whole implementation itself as you suggest. I thought I could make each component separated but then each one instantiated by that single class, so the user wouldn't have to worry about the dependencies of it. Is it that testable? Or may be the whole idea is not that good? Jun 28, 2015 at 9:46
  • 1
    @AdriánPérez There are various things you can do to make it more testable. Generally, injecting dependencies is easier to test, which is why IOC containers, like ninject are so popular, you can also do it manually, by having constructors that take parameters and use the dependency if injected, or default to creating the dependency if not instantiated, or call out to a factory class to construct the object. There's a constant balance to be found between encapsulating the functionality and allowing it to be testable. Usually you result in more abstractions if you're going down a tdd route.
    – forsvarir
    Jun 28, 2015 at 12:16
  • Thanks @forsvarir, I'll take a look at the IOC containers. I also like the idea of the factory class. Jun 28, 2015 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.