Reputation: 564
I'm writing some test cases for my C++ project using Microsoft::VisualStudio::CppUnitTestFramework. Here I have a case where I have to run a same test case with different parameters.
In Nunit Framework for CPP, I can achieve this by the following code.
[Test, SequentialAttribute]
void MyTest([Values("A", "B")] std::string s)
{
}
By passing these parameters, this test will run 2 times.
MyTest("A")
MyTest("B")
Is there a similar way to achieve this in Microsoft::VisualStudio::CppUnitTestFramework unit test.
Any help is highly appreciated.
Upvotes: 4
Views: 2381
Reputation: 300
Quick and simple solution:
Create a vector with your test cases in TEST_METHOD_INITIALIZE, then iterate over the vector in each test case.
#include "stdafx.h"
#include "CppUnitTest.h"
#include <vector>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace SomeTests
{
TEST_CLASS(Some_Tests)
{
public:
std::vector<int> myTestCases;
TEST_METHOD_INITIALIZE(Initialize_Test_Cases)
{
myTestCases.push_back(1);
myTestCases.push_back(2);
myTestCases.push_back(3);
}
TEST_METHOD(Test_GreaterThanZero)
{
for (auto const& testCase : myTestCases)
{
Assert::IsTrue(testCase > 0);
}
}
};
}
Upvotes: 0
Reputation: 3511
The CppUnitTestFramework doesn't provide for parameterized tests, but there's nothing to prevent you from simply writing a parameterized function and calling it from your tests.
void MyTest(char *param)
{
// Actual test code here
}
TEST_METHOD(MyTest_ParamA)
{
MyTest("A");
}
TEST_METHOD(MyTest_ParamB)
{
MyTest("B");
}
Upvotes: 4
Reputation: 448
I had a similar problem: I have an interface and several implementations of it. Of course I do only want to write tests against the interface. Also, I do not want to copy my tests for each implementation. Therefore, I searched for a way to pass parameters to my test. Well, my solution is not very pretty but it is straightforward and the only one I came up with until now.
Here is my solution for my problem (in your case CLASS_UNDER_TEST would be the parameter you want to pass into the test):
setup.cpp
#include "stdafx.h"
class VehicleInterface
{
public:
VehicleInterface();
virtual ~VehicleInterface();
virtual bool SetSpeed(int x) = 0;
};
class Car : public VehicleInterface {
public:
virtual bool SetSpeed(int x) {
return(true);
}
};
class Bike : public VehicleInterface {
public:
virtual bool SetSpeed(int x) {
return(true);
}
};
#define CLASS_UNDER_TEST Car
#include "unittest.cpp"
#undef CLASS_UNDER_TEST
#define CLASS_UNDER_TEST Bike
#include "unittest.cpp"
#undef CLASS_UNDER_TEST
unittest.cpp
#include "stdafx.h"
#include "CppUnitTest.h"
#define CONCAT2(a, b) a ## b
#define CONCAT(a, b) CONCAT2(a, b)
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
TEST_CLASS(CONCAT(CLASS_UNDER_TEST, Test))
{
public:
CLASS_UNDER_TEST vehicle;
TEST_METHOD(CONCAT(CLASS_UNDER_TEST, _SpeedTest))
{
Assert::IsTrue(vehicle.SetSpeed(42));
}
};
You will need to exclude „unittest.cpp“ from build.
Upvotes: 0