Aaron Thomas
Aaron Thomas

Reputation: 5281

Unit testing D library

The built-in unit testing functionality (unittest {...} code blocks) seems to only be activated when running.

How can I activate unit tests in a library with no main function?

This is somewhat related to this SO question, although the accepted answer there deals with a workaround via the main function.

As an example, I would expect unit testing to fail on a file containing only this code:

int foo(int i) { return i + 1; }

unittest {
  assert(foo(1) == 1); // should fail
}

You'll notice I don't have module declared at the top. I'm not sure if that matters for this specific question, but in reality I would have a module statement at the top.

Upvotes: 3

Views: 134

Answers (1)

Vladimir Panteleev
Vladimir Panteleev

Reputation: 25197

How can I activate unit tests in a library with no main function?

You can use DMD's -main switch, or rdmd's --main switch, to add an empty main function to the set of compiled source files. This allows creating a unit test binary for your library.

If you use Dub, dub test will do something like the above automatically.

Upvotes: 4

Related Questions