Sriram Subramanian
Sriram Subramanian

Reputation: 2753

what is the best way to write unit tests for a c++ lib from c#?

Assume that there are many managed modules that call into unmanaged modules. The test framework tests the managed module. I would like to test the independent c++ modules in the lib but make it run as part of the current test framework. Currently, I am thinking of using a c++ unit test framework and using pinvoke to call the unit test main method from the c# test framework. The c++ will output its results to the console and finally return success or failure to the managed test framework. Any suggestions?

Upvotes: 1

Views: 381

Answers (2)

Eric
Eric

Reputation: 11662

I agree with Timo's suggestion that you would be better off using only a single test framework. But instead of a C++/CLI shim, which requires introducing some new technology and can raise difficult marshaling issues, my choice would be to find a way to invoke the tests directly via p/Invoke. So I would write the shim code in C++ using either (or both) of two approaches:

  • Where possible, write all the test logic in C#, so that the shim functions just lightly wrap your existing C++ logic, and the C# code invokes them just as the C++ code would. (This is particularly easy if you factor your C++ functions into a DLL that can be used equally by your main application and your tests. However that may not make sense if your interface is heavily class-oriented rather than being in a WINAPI style. Even then however, it's sometimes easy enough to write WINAPI shims that wrap a class interface, passing this around as an LPVOID.) Anyway, the point is to write as little new C++ as possible.

  • For code where the bulk of the test logic only makes sense to write in C++, a single WINAPI function per test that executes the test steps and returns a result (for example, returns true/false and populates an error string, or possibly throws an exception).

Upvotes: 0

Timo Geusch
Timo Geusch

Reputation: 24341

I would be tempted to write a C++/CLI shim so you can invoke your unit tests directly from the current .NET test framework rather than bring s second one into the picture and try to mix and match the results.

Upvotes: 2

Related Questions