Unit testing your code

Unit tests are blocks of code that verify the correct output of one small part of your code (a unit) at a time, such as an individual function or class. D has a built-in support for basic unit testing. Here, we'll see what we can do with it.

How to do it…

Perform the following steps:

  1. Add unittest {} blocks to your modules, under your functions and inside your classes.
  2. Put any imports needed by the test inside the unittest block.
  3. You should write helper function and class definitions inside the unittest block.
  4. Write assertions to perform your tests.
  5. Use std.exception for additional helper functions.
  6. Compile with dmd –unittest yourfiles.d.
  7. Run the program.

    Tip

    Design your classes with dependency injection for easier mocking of tests. This is when instead of constructing child objects yourself, you accept them as arguments to the constructor. The unit test may then pass a dummy object to the class instead of, for example, a live network connection to test the code.

    Consider the following code snippet:

    unittest {
       assert(myFunction() == expected_value);
    }

How it works…

D's specialized syntax for unit testing was added with a modest goal; to make writing basic unit tests so easy that there's just no excuse not to. They don't aim to do everything possible—there are third-party libraries to extend unit testing capabilities—but do aim to set a usable foundation.

Using them is very simple; you write a unittest {} block and fill it with assert statements to test your code. Use an alternate implementation or manual to figure out the expected values of your functions and compare the results.

Any types or imports you need should be local to the unittest block. This ensures you don't accidentally use these types or imports in non-tested code, which would cause the tests to pass, but the regular build to fail!

Tip

Outside the unittest block, you can use version(unittest) to conditionally compile code only if unit testing is enabled. This can be useful to provide an empty main function to allow your module to be used as a library import or be compiled alone to run its tests. You can also compile with –unittest –main for the compiler to automatically insert an empty main function for you.

You may also use any construct, including loops, conditionals, and exceptions. The unit testing code is just normal D code that is run upon request.

The Phobos module std.exception includes some helper functions to test functions in error conditions. For example, assertThrown can be used to ensure a function throws the proper exception when deliberately given invalid data.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.144.194