Use C++ unit tests on MacOS

By | December 20, 2024

I’ve never written C/C++ code for macOS before, despite using macOS as my primary notebook for daily tasks. It was fascinating to explore how configuration options for header files and libraries work in this environment. As you may recall, in Visual Studio on Windows, you can use various tools to build projects, including the very powerful vcpkg.

On macOS, I started by manually adding all the required C++ dependencies. I decided to use brew for this, so the first step was:

brew install googletest

The next command displays the directories associated with the installed library:

brew ls -v googletest

It outputs something like this:

I began by creating a simple Command Line Tool application,

setting it up as follows, and manually configuring the directories as shown below.

The final step is to point the linker to the correct library names using Other Linker Flags.

For example, on Windows, we could do this with (but I recomend CMake):

#pragma comment( lib libname)

On Windows, using Visual Studio, we can create multiple projects within one solution, select the desired project, and run it independently, including setting breakpoints, etc. Unfortunately, this is not available in Xcode. Instead, we achieve similar functionality by using different targets.

Here’s our project structure:

The main.unittests.cpp file contains the following code:

#include <gtest/gtest.h>
#include <gmock/gmock.h>
 
 
 
TEST(CalculatorTest, AddMethodTest) {
    EXPECT_EQ(2,2);
}
 
 
int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

To set up the project, go to the Targets section and add a new target. Select Command Line Tool, and then, in the Build Phases section under Compile Sources, choose your main unit test file (main.unittests.cpp) as shown below.

Now, simply choose the required target to run your code (tests or application), and everything works as expected.

Leave a Reply