Using Xcode to Unit Test SDL Games Written in C++

November 23rd, 2010

Filed under: SDL, Xcode | Be the first to comment!

Suppose you’re using SDL to program a game. You’re writing the game in C++, and you want to write unit tests for your code. Your first instinct would be to use a C++ unit testing framework like googletest or UnitTest++. Your instinct would be correct on Linux and Windows, but the Mac version of SDL uses Cocoa, which is an Objective-C framework. If you try to unit test your SDL C++ game on a Mac, you’re going to get hundreds of compiler errors related to the Cocoa framework because a C++ unit testing framework doesn’t understand Objective-C. How do you unit test your SDL game on a Mac?

Use Xcode’s built-in support for Objective-C unit testing. Add a Cocoa unit testing bundle target to your project. Add an Objective-C test case class to your project, making sure to add the test case class to the unit testing target, not the target for your SDL game. Give the test case file the extension .mm instead of .m. Giving the file the extension .mm tells Xcode to treat the test case file as an Objective-C++ file, which allows you to unit test your C++ code with¬†OCUnit, the Objective-C unit testing framework that comes with Xcode.

Make sure your game’s C++ source files are members of the unit testing target you created. If you don’t add your game’s C++ files to the unit testing target, you will get linker errors when your unit tests access your game’s classes. Read my googleTest Xcode Tip post for instructions on adding your C++ files to the unit testing target.

Apple’s Xcode Unit Testing Guide, which is part of Apple’s Mac developer documentation, contains additional information on setting up Xcode for unit testing. Also, thanks to Chris Hanson for his answer to a question 5 years ago on one of Apple’s mailing lists. Without his answer I would have never known you could unit test C++ code with OCUnit.

Tags:


Leave a Reply

Your email address will not be published. Required fields are marked *