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.
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");
}
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.
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);
}
}
};
}
Related
I am trying to mock global function using https://github.com/apriorit/gmock-global library.
Note: this description contains example of the real scenario not the exact real scenario. Also I am not allowed to make any changes to global.hpp.
My example dir structure looks like below
--src
------global.hpp
------classA.hpp
------classB.hpp
------main.cpp
--ut
------classATests.cpp
------classBTests.cpp
------main.cpp
The ut/main.cpp tests testcases in classATests.cpp and classBTests.cpp.
global.hpp contains a global function
int giveIndex()
{
return 1;
}
classA.hpp calls giveIndex() global function
#include "global.hpp"
class A
{
public:
int checkIndex() { return giveIndex(); };
}
classB.hpp calls giveIndex() global function
#include "global.hpp"
class B
{
public:
int checkIndex() { return giveIndex(); };
}
classATests.cpp contains
#include <memory>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <gmock-global/gmock-global.h>
#include "src/classA.hpp"
MOCK_GLOBAL_FUNC0(giveIndex, int(void));
using namespace ::testing
struct classATests : public ::testing::Test
{
void Setup() override
{
sut_ = std::make_shared<A>();
}
std::shared_ptr<A> sut_;
};
TEST_F(classATests , checkIndex)
{
EXPECT_GLOBAL_CALL(giveIndex, giveIndex()).WillOnce(Return(1));
sut_->checkIndex();
}
classBTests.cpp contains
#include <memory>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <gmock-global/gmock-global.h>
#include "src/classB.hpp"
MOCK_GLOBAL_FUNC0(giveIndex, int(void));
using namespace ::testing
struct classBTests : public ::testing::Test
{
void Setup() override
{
sut_ = std::make_shared<B>();
}
std::shared_ptr<B> sut_;
};
TEST_F(classBTests , checkIndex)
{
EXPECT_GLOBAL_CALL(giveIndex, giveIndex()).WillOnce(Return(1));
sut_->checkIndex();
}
The issue now is when i compile and run UT for both classATests.cpp and classBTests.cpp i get errors saying
... multiple definition of 'giveIndex' ;
and
... multiple definitions of gmock_globalmock_giveIndex_instance
Is there any way to avoid this issue ? classA tests and classB tests need to be in 2 different files like it is now.
Functions defined in header files should be defined inline
inline int giveIndex()
{
return 1;
}
otherwise you will get multiple definition errors if you include the header file more than once.
The alternative would be to only declare the function in your header file
int giveIndex();
and then define it (but not inline) in one of your cpp files.
This is the normal way to organise C++ code. gmock has nothing to do with this.
I'm new to google mock and I'm trying to mock an interface, but keep getting a linker error with undefined symbols for architecture x86_64
Here's my simplified code:
I have the following in a .h file:
namespace Mynamespace
{
class IMyInterface
{
public:
virtual ~ IMyInterface() {};
virtual void myFunction() = 0;
};
}
this in another .h file:
#include <gmock/gmock.h>
#include <IMyInterface.h>
namespace testing
{
class MyClassMock : public IMyInterface
{
public:
~ MyClassMock();
MyClassMock(int, int, int);
MOCK_METHOD0(myFunction, void());
};
}
and this in my Test Case .cpp file:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <IMyInterface.h>
namespace testing
{
TEST(MyClassMock, myFunction)
{
MyClassMock mcm(0,0,0);
}
}
Do you have an idea what am I doing wrong?
Any help would be very much appreciated!
cheers,
Simon
EDIT:
Unfortunately the mock still doesn't seem to work. After I added the implementation like this:
namespace testing
{
MyClassMock:: MyClassMock(int a, int b, int c)
{
}
MyClassMock::~ MyClassMock()
{
}
}
"myFunction" will not be called when I do
#include "MyClassMock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::AtLeast;
using namespace testing;
TEST(MyClassTest, canCallFunction)
{
MyClassMock mock(0,0,0);
EXPECT_CALL(mock, myFunction())
.Times(AtLeast(1));
}
returning:
EXPECT_CALL(mock, myFunction())
Expected: to be called at least once
Actual: never called - unsatisfied and active
You have to provide implementations for MyClassMock::MyClassMock(int, int, int) and MyClassMock::~MyClassMock().
On a side not, you should use "" rather than <> when you #include your own headers. E.g. #include "IMyInterface.h" not #include <IMyInterface.h>. That way, the compiler will search in the current directory prior to the system include path.
i was wondering if someone could explain me how to use interfaces.
generally, the interface shall be used in every case between layers and architecture objects (allows testability, clear structure/architecture, independently working in teams,....)
What i don't yet understand is, is the include dependency.. i still need to instantiate the object Test itself and therefore need to include it directly in the layer above (arch). But id like rather not to know whats going on down there and only work with the interface.
What is the way to go here?
Does someone have a concrete example (Example: HAL::Timer as Object and HAL:IF_Timer as interface where Middleware/Application whats to create such object and make use of it?
// =============== IF_Test.hpp =======================
#ifndef IF_Test_hpp
#define IF_Test_hpp
#include <stdio.h>
class I_Test
{
public:
I_Test() { };
virtual ~I_Test() { };
virtual std::string& toString() = 0;
};
#endif /* IF_Test_hpp */
// =============== Test.hpp =========================
#ifndef Test_hpp
#define Test_hpp
#include <stdio.h>
#include "IF_Test.hpp"
class Test : public I_Test
{
std::string myName;
public:
Test();
~Test();
std::string& toString();
};
#endif /* Test_hpp */
// =============== Test.cpp =========================
#include <iostream>
#include <cstdio>
#include <string>
#include "Test.hpp"
Test::Test()
: myName("PeterParkerIsBatman")
{
std::cout << "Test\n";
}
Test::~Test()
{
std::cout << "!Test\n";
}
std::string& Test::toString()
{
return myName;
};
// =============== main.cpp =========================
#include <iostream>
#include "IF_Test.hpp"
/** HERE i still need to include the
concrete class object, which id likte NOT to do
(Or do i want this and why?) */
#include "Test.hpp"
int main(int argc, const char * argv[])
{
I_Test * obj = new(Test);
obj->toString();
std::cout << "Hello, World!\n";
return 0;
}
By having a reference to an abstract class member ITimer, you can obtain this abstraction layer you are looking for where the Scheduler doesn't have any knowledge of mTimer implementation.
// =============== ITimer.h =======================
class ITimer {
public:
virtual double time() = 0;
};
// =============== Timer_A.h =======================
//#include ITimer.h
class Timer_A : public ITimer {
public:
double time() override {
/* One way .. */
return {};
}
};
// =============== Timer_B.h =======================
//#include ITimer.h
class Timer_B : public ITimer {
public:
double time() override {
/* Another way .. */
return {};
}
};
// =============== Scheduler.h =======================
//#include ITimer.h <-- No mention of any specific implementation of the ITimer abstract class
class Scheduler{
public:
Scheduler(ITimer& timer)
: mTimer(timer)
{}
void run (){
double time = mTimer.time();
/* etc .. */
}
private:
ITimer& mTimer;
};
// =============== main.cpp =======================
#include Timer_A.h
#include Timer_B.h
#include Manager.h
int main()
{
Timer_A timerA;
Timer_B timerB;
Scheduler schedulerA(timerA);
Scheduler schedulerB(timerB);
}
You can have as many layers like that where the only place where you include the file containing the implementation (Timer_A.h and Timer_B.h) is a the highest level.
Like you said, this lets you change the concrete classes very easily and allows great testing capability using gmock for example.
I am trying to implement the Observer pattern for a game I am creating for a school project.
I have created 2 virtual classes, Observer and Observable.
Observer.h:
#ifndef OBSERVER_H
#define OBSERVER_H
#include <vector>
class Observable;
class Observer
{
public:
Observer();
virtual ~Observer();
virtual void update(Observable* ob) =0;
};
#endif
Observer.cpp:
#include "stdafx.h"
#include "Observer.h"
Observer::Observer()
{
}
Observer::~Observer()
{
}
Observable.h:
#ifndef OBSERVEABLE_H
#define OBSERVEABLE_H
#include <vector>
#include "Observer.h"
class Observable
{
protected:
std::vector<Observer*> observers;
public:
Observable();
virtual ~Observable();
virtual void attach(Observer *a);
virtual void detach(Observer *a);
virtual void notify();
};
#endif
Observable.cpp:
#include "stdafx.h"
#include "Observable.h"
Observable::Observable()
{
}
Observable::~Observable()
{
}
void Observable::attach(Observer *a)
{
observers.push_back(a);
}
void Observable::detach(Observer *a)
{
for (auto it = this->observers.begin(); it < this->observers.end(); it++)
{
if (*it == a)
{
this->observers.erase(it);
break;
}
}
}
void Observable::notify()
{
for (int i = 0; i < observers.size(); i++)
observers[i]->update(this);
}
I have a Map class that inherits from Observable, and a mapView class that inherits from Observer (Map is very long, I only included the relevant functions)
Map.h:
#ifndef MAP_H
#define MAP_H
#include "Observable.h"
#include <iostream>
class Map : public Observable
{
public:
Map();
~Map();
void getLatest();
void notify();
};
#endif
Map.cpp:
#include "stdafx.h"
#include "Map.h"
Map::Map()
{
}
Map::~Map()
{
}
void Map::getLatest()
{
using namespace std;
cout << "This is the latest info!" << endl;
}
mapView.h:
#ifndef MAP_V_H
#define MAP_V_H
#include "Observer.h"
#include "Map.h"
#include "Plants.h"
class mapView : public Observer
{
public:
mapView();
~mapView();
void update(Map* map);
};
#endif
mapView.cpp:
#include "stdafx.h"
#include "mapView.h"
#include "Map.h"
mapView::mapView()
{
}
mapView::~mapView()
{
}
void mapView::update(Map* map)
{
map->getLatest();
}
Finally, my main simply creates a Map and a mapView, attaches the mapView, and calls map.notify()
main.cpp:
#include "stdafx.h"
#include "setUp.h"
#include "Map.h"
#include "mapView.h"
int main()
{
Map gameMap;
mapView view;
gameMap.attach(&view);
gameMap.notify();
return 0;
}
I run into a number of issues here. I cannot create a mapView item because the compiler says I never implemented an override version of update(Observable* ob).... I tried with update(Map* map) but it appears that despite the fact that Map inherits from Observable, it does not seem to count as the same signature, so it won't compile.
I attempted to change my mapView::update() function to take a pointer to Observable instead, but this won't work because the function calls something from Map class.
I then tried changing the update function to NOT be a virtual function (with empty implementation in the virtual class), but it seems any time I try to pass a Map to update, it will call the base class function and not the mapView version. In other words, getLatest() is never called.
I am now pretty confused because this sort of goes against how I thought polymorphism worked. Would appreciate some help or insight if possible!
Thank you,
Your base class declares:
virtual void update(Observable* ob) =0;
You derived class declares:
void update(Map* map);
These are not the same signature. If you used the new override keyword, you would see at compile time that you were not in fact overriding the virtual method.
If you know you'll only get Maps, then you can just use static_cast. But it's safer to use dynamic_cast:
void update(Observable* o) override { // now we're ok
if (auto map = dynamic_cast<Map*>(o)) {
// okay, got a Map
// ....
}
else {
// huh?
}
}
Super brief type theory digression. The typical rule for overrides is covariant in return and contravariant in the argument type. You can specify a more-derived return type, or a more-base argument type. Think about it this way - if you have a base class function taking and returning a Car*... your argument can be a Car* (that's exactly what's expected), or it can be a Vehicle* (since anything you can do with a Vehicle, you can do with a Car - this still works), but it can't be a SportsCar* (since the caller might pass you a Car that isn't a SportsCar and justifiably expect this to work!) It doesn't make sense for the derived class to accept only Maps - you have to be able to accept any Observables, even not Maps!
I’m doing some C++ test driven development. I have a set of classes the do the same thing e.g.
same input gives same output (or should, that’s what I’m try to test). I’m using Visual Studio 2012’s
CppUnitTestFramework. I wanted to create a templated test class, so I write the tests once, and can template in classes as needed however I cannot find a way to do this. My aim:
/* two classes that do the same thing */
class Class1
{
int method()
{
return 1;
}
};
class Class2
{
int method()
{
return 1;
}
};
/* one set of tests for all classes */
template< class T>
TEST_CLASS(BaseTestClass)
{
TEST_METHOD(testMethod)
{
T obj;
Assert::AreEqual( 1, obj.method());
}
};
/* only have to write small amout to test new class */
class TestClass1 : BaseTestClass<Class1>
{
};
class TestClass2 : BaseTestClass<Class1>
{
};
Is there a way I can do this using CppUnitTestFramework?
Is there another unit testing framework that would allow me to do this?
I do not know if there is a way to do this with CppUnitTestFramework,
with which I am unfamiliar, but something you can certainly
do in googletest
is specify an arbitrary list of classes and have the framework
generate (template-wise) the same test(s) for all of them. I think that
would fit your bill.
You can download googletest as source here.
The idiom you will want is:
typedef ::testing::Types</* List of types to test */> MyTypes;
...
TYPED_TEST_CASE(FooTest, MyTypes);
...
TYPED_TEST(FooTest, DoesBlah) {
/* Here TypeParam is instantiated for each of the types
in MyTypes. If there are N types you get N tests.
*/
// ...test code
}
TYPED_TEST(FooTest, DoesSomethingElse) {
// ...test code
}
Study the primer and
the samples. Then go to
the AdvancedGuide
for Typed Tests
Also check out More Assertions
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.
Well, my solution is not very pretty but it is straightforward and the only one I came up with until now.
You could do the same for Class1 and Class2 and then add more specialized tests for each implementation.
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.