An Introduction to Writing a Unit Test In TORQUE

TORQUE uses the check unit test framework. A prerequisite to getting started is probably some basic familiarity with the check framework. For this blog post, specific mechanics of check will be glossed over so please refer to this tutorial if something about the framework needs to be clarified.

Our Structure

If you look at the source directories, you’ll find that each directory has a test directory now. For example, src/lib/Libutils/ has src/lib/Libutils/test. Inside src/lib/Libutils/test/ you’ll find a directory for each source file in Libutils directory. In this blog post we’ll discuss the unit tests for u_mu.c, which are located in the directory src/lib/Libutils/test/u_mu/.

For each specific directory, you’ll notice a few common files:

  • – controls how things are compiled.
  • scaffolding.c – contains the definitions of functions not contained in this file.
  • test_<file>.c: test_u_mu.c e.g. – contains the code specifying how to test this file.

As you write tests for existing files, you’ll find that these already exist and you only need to update them as needed. In most cases, this will including modifying scaffolding.c and the test file. won’t need to be modified in most cases.

As you add tests to the test_*.c file you’ll mostly need to set up appropriate structs, call the function you are testing, and then use fail_unless statements to make sure that you’ve gotten the results you were looking for. Let’s refer to trim_whitespace_test in src/lib/Libutils/test/u_mu/test_u_mu.c.

This function tests the is_whitespace() and trim() functions. As these are relatively simple, its sufficient to simply test the information returned from these functions. For some more complicated functions you may have to test multiple variables affected by the function or even data structures that have been altered in order to be confident that it is working correctly, but looking at these simple cases and working on some can help you become familiar for when you need to unit test more complicated ones.


Picking What Tests To Write

Obviously, its easiest to write a unit test on these simpler, more straightforward functions. These functions can be identified by not having too many dependencies, having one objective, not having too many parameters, or, in general terms, being well-written. Finding these kinds of functions can sometimes be hard, but the key is to find functions as close to this as possible for the your first few unit test forays into TORQUE. As you test more and more you’ll become more confident to test functions that conform less to these ideals.

Facebook Twitter Email

Speak Your Mind