C++ Unit Testing Best Practice

Writing unit tests has a purpose, and the purpose is NOT only to make the building Green. If you want a green build, just return true in your tests and move on. Otherwise, there are several principles you have to follow when you are writing unit tests for your project.

Generally, A unit test should satisfy the AAA Pattern: Arrange, Act, Assert.  That’s at the macro level.

We’ll dig a little bit deeper inside, and give you some strong principles that will make your Unit Tests better.

Test Agenda The key to successful Unit Testing

  • Make your tests Trustworthy
  • Create Maintainable tests
  • Create Readable tests

Avoid Test Logic

  • Use no loops: if/switch/ for/ while etc.
  • A Test should only include creating, configuring, act and asserting actions
  • Remember: Logic in tests leads to test bug

Enforce Test Isolation

  • No dependency between tests
  • Do not run a test from another test
  • Run alone or all together in any order

Create Readable Tests

  • Consistent structure
  • No magic values
  • Naming a Unit Test correctly
  • Separate the Assert from action

Naming a Unit Test

  • Specify what is the test scenario
  • Specify what is the expected behavior return value

For example:

Add_LessThanZero_Throws_Exception

Avoid Multiple Asserts

  • It’s like having multiple tests
  • If one assert fails – all the rest will fail
  • The test will be hard to name
  • Can lead to more debugging work

Removing/Changing Tests

  • Do not change or remove tests, always add new ones
  • Unless:
  • It is for clarity (the functionality remains the same)
  • The test is not needed
  • The test is needed to run differently

Do not repeat Production code

For example:

char user[] = “a”;

char password[] = “b”;

char someResult[] = UnderTest.CreateMessage(user, password);

Assert::AreEqual(user + “,” + password == someResult);

Create maintainable tests

  • Avoid testing private/protected members
  • Re-use code test
  • Test one thing: One mock per test, avoid multiple asserts

Recap: use these best practices for successful C++ unit testing.