Writing tests for C code in Visual Studio 2022

Test 1 passed, Test 2 failed...

Nov 28, 2024

I've been a big fan of using the unity test framework created by ThrowTheSwitch for writing test cases on Linux.

However, I found that Visual Studio has a built-in test framework that can be used to write tests for C code, albeit a little confusing to setup.

Here is a step-by-step guide on how to write tests for C code in Visual Studio 2022:

  1. Add a new project to your solution.
  2. Select Native Unit Test Project.
    • It will say C++ but don't worry, we can still use it for C code.
    • Name this project Tests or something similar.

This will create a new project with a Tests.cpp file, this is where we will write our test cases.

Here is where it gets a little tricky, but bear with me:

  1. In the Tests.cpp file, add the following code:
extern "C"
{
    #include "name_of_your_header_file.h"
    #include "additional_header_files.h"
}

Now for each test case you want to write, simply add a TEST_METHOD block:

#include "pch.h"
#include "CppUnitTest.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace CatTests
{
	TEST_CLASS(CatTests)
	{
	public:
		TEST_METHOD(CatMeow)
		{
            Assert::AreEqual(1, cat_meow());
		}

        TEST_METHOD(CatPurr)
        {
            Assert::AreEqual(1, cat_purr());
        }
	};
}
  1. To build your test cases, be sure to edit the properties of the C/C++ project settings:
    • C/C++ -> General -> Additional Include Directories: Add the path to your header files.
    • C/C++ -> Precompiled Headers -> Precompiled Header: Not Using Precompiled Headers.
    • C/C++ -> Preprocessor -> Preprocessor Definitions: Add any preprocessor definitions you need.
    • Linker -> Input -> Additional Dependencies: Add any additional libraries you need.

Visual Studio should now automatically detect your test cases and run them when you build your solution.