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.
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.
The situation is like this:
//header file
#ifndef CLASSA_H
#define CLASSA_H
#include <stdint.h>
class ClassA
{
public:
void function1();
void function2();
};
#endif //CLASSA_H
//cpp file
#include "ClassA.h"
void ClassA::function1()
{
/* some code */
}
void ClassA::function2()
{
/* some more code */
}
void function3()
{
/* more code /*
}
//main.cpp
#include "ClassA.h"
int main()
{
ClassA obj;
obj.function3();
}
I want to call function3() in main.cpp but without inheritance. I tried using the instance of ClassA but that says "function3 is not a member of classA".
Maybe I'm missing a concept, would be great if anyone can help.
When you try to call function3() with obj.function3() syntax, the compiler then tries to find if there's a function exists named function3 in the instance of the class (i.e. object).
Now, in this case, you can do two things:
Include void function3() in the public: of the class and change void function3() to void ClassA :: function3() to tell the compiler that the containing code is defined for the class member function.
Or, define the function inside the header file and prevent calling the function by defining the class object. It's obvious, isnce you can't access something which is declared outside of the class.
The code explanation of all the two above methods is as follows:
Method 1
ClassA.cpp
#include "ClassA.h"
...
void ClassA::function3() // definition of the class member function
{
/* more code */
}
main.cpp
#include "ClassA.h"
int main()
{
ClassA obj;
obj.function3(); // now it's inside the class member function
// hence, we may now use it
}
ClassA.h
...
class ClassA
{
public:
...
void function3(); // declared inside the class
};
#endif //CLASSA_H
Method 2
ClassA.h
...
void function3()
{
/* more code */
}
main.cpp
#include "ClassA.h"
int main()
{
function3();
}
ClassA.cpp
class {
...
};
void function3()
{
/* more code */
}
But the second method will make the class useless, therefore, possibly you meant to achieve the first method and not the second.
I'm trying to implement dependency injection in a C++ project. However, due to the structure of the dependencies, I'm getting a segmentation fault which I can't solve.
As an example I constructed the following classes and interfaces. I have a class called MyClass which has a dependency on Dependency. Dependency has a dependency on OtherDependency. To allow for proper testing, I inherit the dependencies from an interface, i.e. IDependency and IOtherDependency. OtherDependency has a function some_function().
In main.cpp I create an instance of MyClass and then try to call some_function(). Unfortunately, this gives a segmentation fault:
Segmentation fault (core dumped)
MyClass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
#include "IDependency.h"
class MyClass
{
public:
MyClass(IDependency *dependency);
~MyClass();
IDependency *_dependency = nullptr;
};
#endif
MyClass.cpp:
#include "MyClass.h"
#include <iostream>
MyClass::MyClass(IDependency *dependency) : _dependency(dependency) {}
MyClass::~MyClass() {}
Dependency.h:
#ifndef DEPENDENCY_H
#define DEPENDENCY_H
#include "IDependency.h"
#include "IOtherDependency.h"
class Dependency : public IDependency
{
public:
Dependency(IOtherDependency *other_dependency);
~Dependency();
IOtherDependency *_other_dependency = nullptr;
};
#endif
Dependency.cpp:
#include "Dependency.h"
#include <iostream>
Dependency::Dependency(IOtherDependency *other_dependency) : _other_dependency(other_dependency) {}
Dependency::~Dependency() {}
IDependency.h:
#ifndef IDEPENDENCY_H
#define IDEPENDENCY_H
#include "IOtherDependency.h"
class IDependency
{
public:
IOtherDependency *_other_dependency;
};
#endif
OtherDependency.h:
#ifndef OTHERDEPENDENCY_H
#define OTHERDEPENDENCY_H
#include "IOtherDependency.h"
class OtherDependency : public IOtherDependency
{
public:
OtherDependency();
~OtherDependency();
void some_function();
};
#endif
OtherDependency.cpp:
#include "OtherDependency.h"
#include <iostream>
OtherDependency::OtherDependency() {}
OtherDependency::~OtherDependency() {}
void OtherDependency::some_function()
{
std::cout << "I am OtherDependency." << std::endl;
}
IOtherDependency.h:
#ifndef IOTHERDEPENDENCY_H
#define IOTHERDEPENDENCY_H
class IOtherDependency
{
public:
virtual void some_function() = 0;
};
#endif
main.cpp:
int main()
{
OtherDependency *other_dependency = new OtherDependency;
Dependency *dependency = new Dependency(other_dependency);
MyClass my_class(dependency);
my_class._dependency->_other_dependency->some_function();
}
What am I doing wrong / do I need to change?
You have two variables called _other_dependency: one in IDependency, the other in Dependency. The Dependency constructor initialized the latter, while the one in the IDependency class retains its default nullptr value.
When you access my_class._dependency->_other_dependency, the other_dependency will be the one in IDependency, because _dependency points to the base class.
One way to fix this is to remove the other_dependency from Dependency, and pass the value from the Dependency constructor to IDependency to properly initialize its member.
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);
}
}
};
}
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!