How do I write unit tests for an event driven application managed by libevent?

1.6k views Asked by At

I'm writing an event driven application using the libevent library for asynchronous I/O. Essentially, the application has an evconnlistener listening for data on a port. On receiving data, the data is forwarded to a corresponding http REST end point depending on the data payload. The forwarding component uses evhttp_* provided by libevent.

I'm able to test the application as an external process to satisfy the sanity of the application, however I'm stumped when it comes to generating code coverage reports. How do I go about writing unit tests that can be invoked via regular unit testing frameworks such as cppunit?

1

There are 1 answers

1
John Deters On BEST ANSWER

Add a wrapper layer around the asynchronous I/O calls. You can then substitute a "MockIO" class to feed your tests around handling the I/O connections.

It really sounds like you're describing integration more than unit testing. Unit testing is really about testing each individual module in isolation, not how they all come together to provide system functionality.

One unit test would make sure that data was received from an I/O event. A separate test would make sure that data fed into the REST endpoint was properly received. Another separate test would make sure the REST endpoint was parsing it as desired. Regarding the I/O event tests, I'd add more unit tests to simulate I/O failure, broken connections, and other unhappy paths, all to be sure the exception handling code was functioning properly, and that all lines of code in that module were tested. Similarly I'd also test the endpoint with all kinds of bad inputs: null pointers, empty buffers, really long buffers, unexpected data types, whatever different tests would be needed to exercise all the paths through the method.

We strive for (but don't always achieve) full code coverage in the unit tests. Integration tests show the pieces come together successfully, but we can't always test every interaction. The big assumption is if the unit tests passed, the pieces should work well together regardless of what they're doing.

I'm thinking a book might better help you break through your "stumped" phase by giving you a better overall picture of automated unit testing. If you're trying to add unit tests to an existing project, Michael Feathers' book Working Effectively with Legacy Code is absolutely great (Mike is the author of CppUnit.) If you're just starting out with a small project, The Art of Unit Testing by Roy Osherove is a good read. And once you've gotten the ideas of unit testing down, xUnit Test Patterns by Gerard Meszaros is a great resource to help you learn how to write maintainable tests.

And if you have the opportunity, spend some quality time learning from a mentor.