C++ – Anonymous namespaces make code untestable

cunit testing

Here is a typical C++ code:

foo.hpp

#pragma once

class Foo {
public:
  void f();
  void g();
  ...
};

foo.cpp

#include "foo.hpp"

namespace {
    const int kUpperX = 111;
    const int kAlternativeX = 222;

    bool match(int x) {
      return x < kUpperX || x == kAlternativeX;
    }
} // namespace

void Foo::f() {
  ...
  if (match(x)) return;
  ...

It looks like a decent idiomatic C++ code – a class, a helper function match which is used by the methods of Foo, some constants for that helper function.

And then I want to write tests.
It would be perfectly logical to write a separate unit test for match, because it's quite non-trivial.
But it resides in an anonymous namespace.
Of course I can write a test which would call Foo::f(). However it won't be a good test if Foo is heavy and complicated, such test won't isolate the testee from other unrelated factors.

So I have to move match and everything else out of the anonymous namespace.

Question: what's the point of putting functions and constants into the anonymous namespace, if it makes them unusable in tests?

Best Answer

If you want to unit-test the private implementation-details, you do the same sort of dodge for unnamed namespaces as for private (or protected) class-members:

Break in and party.

While for classes you abuse friend, for unnamed namespaces you abuse the #include-mechanism, which doesn't even force you to change the code.
Now that your test-code (or better only something to expose everything) is in the same TU, there's no problem.

A word of caution: If you test the implementation-details, your test will break if those change. Be really sure to only test those implementation-details which will leak anyway, or accept that your test is unusually ephemeral.