I'm trying to become familiar with Google's mocking framework so I can more easily apply some TDD to my C++ development. I have the following interface:
#include <string>
class Symbol {
public:
Symbol (std::string name, unsigned long address) {}
virtual ~Symbol() {}
virtual std::string getName() const = 0;
virtual unsigned long getAddress() const = 0;
virtual void setAddress(unsigned long address) = 0;
};
I want to verify that the destructor is called when an instance is deleted. So I have the following MockSymbol class:
#include "gmock/gmock.h"
#include "symbol.h"
class MockSymbol : public Symbol {
public:
MockSymbol(std::string name, unsigned long address = 0) :
Symbol(name, address) {}
MOCK_CONST_METHOD0(getName, std::string());
MOCK_CONST_METHOD0(getAddress, unsigned long());
MOCK_METHOD1(setAddress, void(unsigned long address));
MOCK_METHOD0(Die, void());
virtual ~MockSymbol() { Die(); }
};
Note: I've omitted the include guards in the above but they are in my header files.
I haven't been able to get to a point where I'm actually testing anything yet. I have the following:
#include "gmock/gmock.h"
#include "MockSymbol.h"
TEST(SymbolTableTests, DestructorDeletesAllSymbols) {
::testing::FLAGS_gmock_verbose = "info";
MockSymbol *mockSymbol = new MockSymbol("mockSymbol");
EXPECT_CALL(*mockSymbol, Die());
}
When I execute my test runner, my other tests execute and pass as I expect them to. However, when the above test executes I get the following error:
SymbolTableTests.cpp:11: EXPECT_CALL(*mockSymbol, Die()) invoked
Segmentation fault (core dumped)
I've spent the last few hours searching Google and trying different things, but to know avail. Does anyone have any suggestions?
I found that setting gtest_disable_pthreads to ON in my build config solves the problem.
Related
So I've got this interface class that I include, both in the dll and the client project
// InterfaceClass.h
#pragma once
class InterfaceClass
{
public:
virtual void Update() = 0;
};
This is the dll class that calls one of its own methods inside update
// DLLClassThatDoesSomething.cpp
#include "InterfaceClass.h"
#include <iostream>
#include <string>
class __declspec(dllexport) DLLClass : public InterfaceClass
{
public:
void Update()
{
std::cout << this->GetString();
}
std::string& GetString()
{
std::string thestring = "bruhmoment";
return thestring;
}
};
extern "C"
{
__declspec(dllexport) InterfaceClass* CreateInstance()
{
return new DLLClass();
}
}
And this is the "Client" project
// main.cpp
#include "InterfaceClass.h"
#include <Windows.h>
typedef InterfaceClass* (__cdecl *Class) ();
int main()
{
HINSTANCE dll = LoadLibrary(L"DLLClass.dll");
Class klass = (Class)GetProcAddress(dll, "CreateInstance");
InterfaceClass* IKlass = klass();
IKlass->Update();
FreeLibrary(dll);
return 0;
}
The moment I call IKlass->Update() I get an exception for Access Memory Violation because of the DLLClass calling its own method.
I haven't tried anything since I barely know how to load a DLL on runtime and I've used this nifty tutorial
How can I let it call the method and not get thrown an exception? I'm trying to let ppl that will create mods for my game create their own mods with their custom classes for bosses, mobs and etc. in DLLs.
EDIT:
Turns out it was a syntax mistake on my end. Instead of return new DLLClass;, it had to be return new DLLClass();. After fixing it, it works as intended.
You return a reference to a local variable thestring, and by the time you try to access it in
std::cout << this->GetString(), referenced data is already destroyed. In fact, it is destroyed right after the end of enclosing scope of compound statement where the variable was declared.
It may "appear" to work sometimes due to the stack not being overwritten yet, but eventually it will fail miserably like it did in your case. This triggers UB (undefined behavior).
I am working on a circuit simulator/pathfinding system, but I keep getting these weird compilation errors. I am not yet that experienced with OO C++ to figure it out myself...
Object Tree
The objects in my project are implemented in this way:
Object
Component
Wire
Switch
Ciruit
My Object class is the base class for everything in my project, this is great for debugging by giving everything a name and an id.
I required that every component needs a Circuit to with (see it as a parent for components). I implemented this by creating a constructor in the Component class that requires a reference to a Circuit object.
At first, everything worked and compiled fine, but when I introduced the Circuit class and when I added a constructor in Component with a Circuit reference parameter, everything went wrong...
Compilation errors
Now I keep getting these seemingly random syntax and missing tokens errors. (Intellisense does not mark them?)
The first four errors that pop up are:
C2238: unexpected token(s) preceding ';'.
At line 10 of Component.hpp. And at line 12 in file Circuit.hpp.
Both just after the constructor definition. (See in code below)
The next four errors point tot the same locations, but it notes:
C2143: syntax error: missing ';' before '*'.
Then, 30 more errors follow, but I think they are a result of these errors, to be sure, here they are:
(Lol, cannot embed image, caused by not having enough reputation, so a link instead...)
Click here for errors
What I tried
I tried the following:
Using a reference instead of pointer. (changed Circuit* c to Circuit& c)
Removing the name string concationation thing in constructor initializer list. (changed ... : Object(name + "blah") to ... : Object(name))
Rewriting the whole Visual Studio project to a new Visual Studio project.
Placing the constructor initializer list in the header file.
Lots of googling... and not lots of solving...
How to fix?
This frustrating problem is stopping me from working further on this project, what is causing it and how do I fix it? I would be pretty happy to know.
Object.hpp
#pragma once
#include <string>
using std::string;
class Object
{
public:
Object();
Object(string name);
string name;
const int id;
virtual string toString();
private:
static int currentId;
};
Object.cpp
#include "Object.hpp"
int Object::currentId = 0;
Object::Object() : id(++Object::currentId), name("Object")
{ }
Object::Object(string name) : id(++Object::currentId), name(name)
{ }
string Object::toString()
{
return name + "#" + std::to_string(id);
}
Component.hpp
#pragma once
#include "Object.hpp"
#include "Circuit.hpp"
class Component : public Object
{
public:
Component(std::string name, Circuit* container);
Circuit *container; // <- Error points to the beginning of this line
};
Component.cpp
#include "Component.hpp"
Component::Component(string name, Circuit* container) : Object(name), container(container)
{ }
Switch.hpp
#pragma once
#include "Component.hpp"
#include "Wire.hpp"
class Switch : public Component
{
public:
Switch(string name, Circuit* container, Wire& wire1, Wire& wire2);
Wire* wire1;
Wire* wire2;
void setEnabled(bool enabled);
bool getEnabled();
private:
bool enabled;
};
Switch.cpp
Switch::Switch(string name, Circuit* container, Wire& wire1, Wire& wire2) : Component(name + "-Switch", container), wire1(&wire1), wire2(&wire2), enabled(false)
{ }
...
Circuit.hpp
#pragma once
#include "Object.hpp"
#include "Wire.hpp"
class Circuit : public Object
{
public:
Circuit(std::string name);
Wire* powerWire; // <- Error points to the beginning of this line
bool isPowered(Wire& wire);
bool getActive();
void setActive(bool active);
private:
bool active;
};
Circuit.cpp
#include "Circuit.hpp"
#include "Util.hpp"
Circuit::Circuit(string name) : Object(name + "-Circuit")
{
active = false;
powerWire = new Wire(name + "-PowerWire", this);
}
...
You haven't shown Wire.hpp, but my guess is that it includes Component.hpp, which gives you a cycle in header inclusion (because Component.hpp includes Circuit.hpp, and Circuit.hpp includes Wire.hpp).
You will have to replace some of these inclusions with forward declarations to break the cycle.
I have been trying hard but could not search any relevant help from online resources. Being new to UT, thus I guess my best choice is to ask here directly. If you do not have direct answer, any relevant resource link is also much appreciated.
My problems sound like this:
//My environment is in C++
//The below code snippet is for reader to understand why I encounter build errors and how should I resolve
//Source code .cpp file (target to run UT on)
class realChild : public virtualParent
{
public:
bool member_func (const OtherNamespace::CustomizedParams &sParams,
int other_Params,
char other_Params2) const;
}
//Header .h file - the class interface
class virtualParent
{
virtual bool member_func (const OtherNamespace::CustomizedParams &sParams,
int other_Params,
char other_Params2) const = 0;
}
//UT .cpp file - the place that I wanted to mock the class to perform unit test
#include "OtherNamespace.h"
using OtherNamespace
class MockrealChild : public virtualParent
{
public:
MOCK_METHOD3(member_func, bool(const CustomizedParams, int, char));
}
Ended up with build errors like this, where I could not find any constructive suggestion to overcome.
error: forward declaration of 'OtherNamespace::CustomizedParams'
First: My English is not that good yours is. Excuse me.
I'm using Ubuntu (I don't know if this is important) and I had issues with Code::Blocks since I started to use it. But I fixed them by re-opening the program. But now, I get a really crazy error when compiling the code. I included a file just like usual:
#include "GameObjectUtility.h"
and I used the class "GameObjectUtility" to declare a member object, just like this:
class GameObject
{
std::vector<GameObjectUtility> uts;
// Error here:
// GameObjectUtility was not declared in this scope
}
So, is this my fault or is there something buggy with Code::Blocks?
And, additionally, is there a way of saying to the Linker: First execute this file and then the other?
Thank you for your answers!
EDIT: .h and .ccp file GameObjectUtility:
So this is GameObjectUtility.h:
#ifndef GAMEOBJECTUTILITY_H
#define GAMEOBJECTUTILITY_H
#include <string>
#include "Collision.h"
class GameObjectUtility
{
public:
GameObjectUtility();
virtual ~GameObjectUtility();
virtual void Update() = 0;
virtual void LateUpdate() = 0;
virtual void FixedUpdate() = 0;
static void SendMsg(std::string msg);
protected:
private:
virtual void GetMsg(std::string msg) = 0;
};
#endif // GAMEOBJECTUTILITY_H
And in GameObjectUtility.cpp are just two empty definitions of constructor and destructor
Since class GameObjectUtility is pure virtual, you cannot instantiate it.
You can only store std::vector<GameObjectUtility*> in class GameObject.
I'm trying to do up a screen scraping assignment. My cpp works, but I don't know how to integrate my unit testing. I tried to do a bool check unit test for the file validity but it's giving me this error:
error: cannot call member function 'bool ScreenScrape::getFile()' without object
screenscrape.cpp:
#include "screenscrape.h"
using namespace std;
int main()
{
ScreenScrape ss;
int choice;
...
...
ss.matchPatternTest();
}
screenscrape.h:
class ScreenScrape
{
public:
ScreenScrape();
void parserTest(int choice);
void matchPatternTest();
void setIndexValue(string data, string IndexName);
void setIndexChange(string data);
void setIndexPercent(string data);
void setIndexDate(string data);
bool getFile();
private:
string IndexName;
string IndexValue;
string IndexChange;
string IndexPercent;
string IndexVID;
string IndexCID;
string IndexPID;
string IndexDate;
};
bool ScreenScrape::getFile()
{
string file1 = "yahoofinance.htm";
char* file2 = new char [file1.size()+1]; // parse file for c string conversion
strcpy(file2, file1.c_str()); // converts to c string
ifstream fin;
fin.open(file2);
if(fin.good())
return true;
else
return false;
}
screenscrapetest.cpp:
#include "screenscrapetest.h"
#include "screenscrape.h"
CPPUNIT_TEST_SUITE_REGISTRATION (ScreenScrapeTest);
void ScreenScrapeTest::fileTest()
{
CPPUNIT_ASSERT(ScreenScrape::getFile()); // test file validity
}
screenscrapetest.h:
#ifndef _SCREENSCRAPETEST_H
#define _SCREENSCRAPETEST_H
#include <cppunit/TestCase.h>
#include <cppunit/extensions/HelperMacros.h>
#include "screenscrape.h"
class ScreenScrapeTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE (ScreenScrapeTest);
CPPUNIT_TEST (fileTest);
CPPUNIT_TEST_SUITE_END ();
public:
void fileTest();
};
#endif
I tried to declare "ScreenScrape ss;" under screenscrapetest.h, use an object (ss) to call getFile() but it's giving me multiples of this error:
/home/user/NetBeansProjects/Assignment1/screenscrape.h:259: multiple definition of `ScreenScrape::getFile()'
I only want to check for file validity with unit testing. Any help will be appreciated.
Thanks in advance!
Regards,
Wallace
bool ScreenScrape::getFile() is not static, so cannot be called as a static function. You'll need to either (a) declare it as static or (b) create an instance of ScreenScrape and call getFile() from it.
Looking at the code, it's not obvious why this function is a method of the class but perhaps it's still in the early stages of development. It can also be refactored to remove lots of redundant code:
bool ScreenScrape::getFile()
{
std::ifstream fin("yahoofinance.htm");
return fin.good();
}
Don't forget your include guards in screenscrape.h:
#ifndef SCREENSCRAPE_H
#define SCREENSCRAPE_H
// Class declaration here...
#endif//ndef SCREENSCRAPE_H
And consider moving the implementation of getFile to the cpp source file. These two steps will prevent you getting the "multiple declaration" errors.
This will fix your compilation errors, but checking for file validity is not a responsibility of a unit test. Unit tests should not interact with the filesystem.
If you're going to be calling ScreenScrape::getfile()rather than ss.getfile(), then getfile() needs be defined as static. The error you're getting is because non-static methods need to be called on a specific object.
It's difficult to track down the error with your version that defines a ScreenScrape object and then uses that to call getfile(); you obviously haven't included all the relevant code since your screenscrape.h file doesn't have 259 lines, and you also haven't shown the revised code in which you "use an object (ss) to call getFile()".