CppUnit : Not able to write test cases - c++

I have written cppUnit codes in testBMath.cc. I am able to write test cases for first three functions which are add,subtract and multiply. But I am not able to write test cases for Divide and Swap.I don't know how to handle divide by zero in test cases and how to check that numbers are swapped or not in cppUnit test cases.
testMath.h
#ifndef TEST_MATH_H__
#define TEST_MATH_H__
class testMath
{
public:
int Addition(int x, int y);
int Multiply(int x, int y);
int Subtraction(int x, int y);
int Division(int x, int y);
void swap(int &x, int &y);
};
#endif
testMath.cc
#include "testMath.h"
int testMath::Addition(int x, int y)
{
return (x + y);
}
int testMath::Multiply(int x, int y)
{
return (x * y);
}
int testMath::Subtraction(int x, int y)
{
return (x - y);
}
int testMath::Division(int x, int y)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
void swap(int &a, int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
testBMath.cc
#include <iostream>
#include <string>
#include <list>
#include "cppunit/TestCase.h"
#include "cppunit/TestFixture.h"
#include "cppunit/ui/text/TextTestRunner.h"
#include "cppunit/extensions/HelperMacros.h"
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/CompilerOutputter.h"
#include "netinet/in.h"
#include "testMath.h"
using namespace CppUnit;
using namespace std;
//-----------------------------------------------------------------------------
class testBMath : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(testBMath);
CPPUNIT_TEST(testAddition);
CPPUNIT_TEST(testMultiply);
CPPUNIT_TEST(testSubtraction);
CPPUNIT_TEST(testDivision);
CPPUNIT_TEST(testSwap);
CPPUNIT_TEST_SUITE_END();
public:
void setUp(void);
void tearDown(void);
protected:
void testAddition(void);
void testMultiply(void);
void testSubtraction(void);
void testDivision(void);
void testSwap(void);
private:
testMath *mTestObj;
};
//-----------------------------------------------------------------------------
void testBMath::setUp(void)
{
mTestObj = new testMath();
}
void testBMath::testAddition(void)
{
CPPUNIT_ASSERT(5 == mTestObj->Addition(2,3));
}
void testBMath::testMultiply(void)
{
CPPUNIT_ASSERT(6 == mTestObj->Multiply(2,3));
}
void testBMath::testSubtraction(void)
{
CPPUNIT_ASSERT(2 == mTestObj->Subtraction(5,3));
}
void testBMath::testDivision(void)
{
CPPUNIT_ASSERT(6 == mTestObj->Division(12,2));
//But for divide by zero how should I write
}
void testBMath::testSwap(void)
{
//How should I check for swap
}
void testBMath::tearDown(void)
{
delete mTestObj;
}
//-----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( testBMath );
int main(int argc, char* argv[])
{
// informs test-listener about testresults
CPPUNIT_NS::TestResult testresult;
// register listener for collecting the test-results
CPPUNIT_NS::TestResultCollector collectedresults;
testresult.addListener (&collectedresults);
// register listener for per-test progress output
CPPUNIT_NS::BriefTestProgressListener progress;
testresult.addListener (&progress);
// insert test-suite at test-runner by registry
CPPUNIT_NS::TestRunner testrunner;
testrunner.addTest (CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest ());
testrunner.run(testresult);
// output results in compiler-format
CPPUNIT_NS::CompilerOutputter compileroutputter(&collectedresults, std::cerr);
compileroutputter.write ();
// return 0 if tests were successful
return collectedresults.wasSuccessful() ? 0 : 1;
}

My suggestions, change exception from const char* to something more meaningful, like std::runtime_error:
int testMath::Division(int x, int y)
{
if( b == 0 )
{
throw std::runtime_error("Division by zero condition!");
}
return (a/b);
}
Than the test's would look like:
void testBMath::testDivision(void)
{
CPPUNIT_ASSERT(6 == mTestObj->Division(12,2));
CPPUNIT_ASSERT_THROW(mTestObj->Division(12,0), std::runtime_error);
}
void testBMath::testSwap(void)
{
int x = 2;
int y = 3;
mTestObj->swap(x, y);
CPPUNIT_ASSERT(x == 3 && y == 2);
}

Related

Nested map with same class

I would like to write a class that stores recursively the same class in a map.
I have the following source codes:
/* A.hpp */
#include <iostream>
#include <string>
#include <map>
class A
{
private:
int a;
std::map<int, A> data;
bool finishCycle;
public:
A(const int& input ) : a(input), finishCycle(false)
{
func1();
}
void func1();
};
/* A.cpp */
void A::func1()
{
A tmp(*this);
while(!finishCycle)
{
a--;
if (a == 0)
finishCycle=true;
else
func1();
}
data.emplace(tmp.a, tmp);
}
/* main.cpp*/
#include "A.hpp"
int main(int argCount, char *args[])
{
A myObj1 (3);
std::cout << "tst" << std::endl;
return 0;
}
This is putting all the entries in the main map. I would like to have it in a nested sequence:
first entry: <1, A>
inside first entry: <2,A>
inside inside first entry <3,A>
How can I change the script to do this? The nested loops still make me confused.
Maybe this is what you want?
#include <iostream>
#include <map>
class A
{
private:
std::map<int, A> data;
public:
A(int n, int i = 0) {
if (n == i) {
return;
}
data.emplace( i+1, A(n, i + 1) );
}
void test() {
if (!data.empty()) {
std::cout << data.begin()->first << "\n";
data.begin()->second.test();
}
}
};
int main()
{
A a(4);
a.test();
}
I came up with:
#include <iostream>
#include <map>
class A
{
private:
int a;
std::map<int, A> data;
bool finishCycle;
public:
A(const int& input ):a(input), finishCycle(false)
{
func1(*this);
}
void func1(A& tmp);
};
void A::func1(A& tmp)
{
A tmp2(tmp);
tmp2.a--;
while(!finishCycle)
{
if (tmp2.a == 0)
{
(*this).finishCycle=true;
}
else
{
func1(tmp2);
}
}
tmp.data.emplace(tmp2.a, tmp2);
}
int main(int argCount, char *args[])
{
A myObj1 (4);
std::cout << "tst" << std::endl;
return 0;
}

Duplicate issue with callbacks

I have the following code and I want to know how duplicate issue for lines 33-38 with 47-52 cand be solved.
struct X has 2 methods with same signature and Y has an instance of X and has 2 methods which has to use the same callback which has to capture same values for the methods from X.
#include <iostream>
#include <functional>
using namespace std;
struct X
{
void func(std::function<void(int)>f, int x)
{
f(x);
}
void func2(std::function<void(int)>f, int x)
{
f(x);
}
};
struct Y
{
void doSomething_1()
{
int x = 10;
bool called = false;
x_.func(
[&x, &called](int xx) // line 33
{ // line 34
called = true; // line 35
x++; // line 36
xx++; // line 37
} // line 38
, 20);
}
void doSomething_2()
{
int x = 10;
bool called = false;
x_.func2(
[&x, &called](int xx) // line 47
{ // line 48
called = true; // line 49
x++; // line 50
xx++; // line 51
} // line 52
, 20);
}
X x_;
};
int main()
{
Y y;
y.doSomething_1();
y.doSomething_2();
return 0;
}
How about The Standard Solution – add a level of indirection?
struct Y
{
void doSomething_1()
{
int x = 10;
bool called = false;
x_.func([this, &x, &called](int xx) { wrapper(x, called, xx); }, 20);
}
void doSomething_2()
{
int x = 10;
bool called = false;
x_.func([this, &x, &called](int xx) { wrapper(x, called, xx); }, 20);
}
X x_;
void wrapper(int&x, bool& called, int xx) { called = true; x++; xx++; }
};
or
struct Y
{
void doSomething_1()
{
int x = 10;
bool called = false;
x_.func(wrapper(x, called), 20);
}
void doSomething_2()
{
int x = 10;
bool called = false;
x_.func(wrapper(x, called), 20);
}
X x_;
std::function<void(int)> wrapper(int&x, bool& called)
{
return [&x, &called](int xx) {called = true; x++; xx++; };
};
};
It is a little bit more difficult than expected, because you are capturing different variables in the 2 functions.
You can use std::bind with a function for that:
#include <iostream>
#include <functional>
using namespace std;
struct X
{
void func(std::function<void(int)>f, int x)
{
f(x);
}
void func2(std::function<void(int)>f, int x)
{
f(x);
}
};
void your_func(int xx, bool &called, int &x)
{
called = true;
x++;
xx++;
}
struct Y
{
void doSomething_1()
{
int x = 10;
bool called = false;
auto func = std::bind(&your_func, std::placeholders::_1, called, x);
x_.func(func, 20);
}
void doSomething_2()
{
int x = 10;
bool called = false;
auto func = std::bind(&your_func, std::placeholders::_1, called, x);
x_.func2(func, 20);
}
X x_;
};
int main()
{
Y y;
y.doSomething_1();
y.doSomething_2();
return 0;
}
https://godbolt.org/z/5ee5ehcsh
You can also std::bind to a member function: https://godbolt.org/z/f9snPbKeW
I must admit that I always hated things like bind() since I learnt them first in combination with sigc++. (I never could remember the correct order to apply them, especially if combined with hide().)
With the introduction of lambdas, all the trouble was gone immediately (and I soon became a fan of lambdas).
A lambda in turn just resembles a function or functor. So, to add to mch's answer, the lambda could be turned into a re-usable functor which is embedded into OPs class Y:
#include <iostream>
#include <functional>
using namespace std;
struct X
{
void func(std::function<void(int)>f, int x)
{
f(x);
}
void func2(std::function<void(int)>f, int x)
{
f(x);
}
};
struct Y
{
struct Count {
int& x;
bool& called;
Count(int& x, bool& called): x(x), called(called) { }
void operator()(int xx) // line 33
{ // line 34
called = true; // line 35
x++; // line 36
xx++; // line 37
}
};
void doSomething_1()
{
int x = 10;
bool called = false;
x_.func(Count(x, called), 20);
}
void doSomething_2()
{
int x = 10;
bool called = false;
x_.func2(Count(x, called), 20);
}
X x_;
};
int main()
{
Y y;
y.doSomething_1();
y.doSomething_2();
return 0;
}
Live Demo on coliru

Error invalid new-expression of abstract class type FancyPlayer cpp

i have this code at main.cpp :
#include <iostream>
#include <limits>
#include <conio.h>
#include "Ghost/SmartGhost/SmartGhost.h"
#include "Player/Player.h"
#include "PlayerInfo/PlayerInfo.h"
#include "GameBoard/GameBoard.h"
#include "ManualPlayer/ManualPlayer.h"
#include <vector>
using namespace std;
class Position {
public:
int x;
int y;
Position();
Position(int xo,int yo) {x=xo; y=yo;} };
class FancyPlayer : public Player
{
private: vector<Position> visited; //vector of visited nodes int size[2]; //width and height of maze Position start; vector <Position> path; //last visited node(backtrack) public:
void init(int width,int height,int x,int y) {
size[0]=width;
size[1]=height;
start.x=x; //starting position
start.y=y; visited.push_back(Position(start.x,start.y)); path.push_back(Position(start.x,start.y)); }
bool isValid(char ** ViewAround,int x,int y) {
return (ViewAround[x][y]!='#' && ViewAround[x][y]!='*'); }
bool isvisited(int x,int y){
bool f=false;
for(int i=0;i<visited.size();i++) {
if (visited[i].x==x && visited[i].y==y)
f=true;
} return f; }
int getMove(char** ViewAround) {
if (isValid(ViewAround,1,2) && !isvisited(start.x-1,start.y))
{
visited.push_back(Position(start.x-1,start.y));
path.push_back(Position(start.x-1,start.y));
start.x--;
return 0; }
else if (isValid(ViewAround,3,2) && !isvisited(start.x+1,start.y))
{
visited.push_back(Position(start.x+1,start.y));
path.push_back(Position(start.x+1,start.y));
start.x++;
return 1; } else if (isValid(ViewAround,2,3) && !isvisited(start.x,start.y+1))
{
visited.push_back(Position(start.x,start.y+1));
path.push_back(Position(start.x,start.y+1));
start.y++;
return 2; } else if (isValid(ViewAround,2,1) && !isvisited(start.x,start.y-1))
{
visited.push_back(Position(start.x,start.y-1));
path.push_back(Position(start.x,start.y-1));
start.y--;
return 3; } else
{
if (path[path.size()-1].x<start.x){
path.pop_back();
start.x++;
return 1;
}
if (path[path.size()-1].x>start.x){
path.pop_back();
start.x--;
return 0;
}
if (path[path.size()-1].y<start.y){
path.pop_back();
start.y++;
return 2; }
if (path[path.size()-1].y>start.y){
path.pop_back();
start.y--;
return 3;
}
}
}
std::string getName() { return std::string("mplampla"); }
std::string getId() { return std::string("cs141065"); }
};
int main() {
std::vector<ObjectInfo *> PlayersVector; //vector with players engaged
PlayersVector.push_back(new PlayerInfo(*new FancyPlayer(), 'A')); //Erase the comments to play with keyboard
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'B')); //Fool Standby player
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'C')); //Fool Standby player
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'D')); //Fool Standby player
GameBoard *MainGameObject; //Main Game Object
InfoBoard *ptrToInfoBoard = new InfoBoard();
for (int j = 0; j < PlayersVector.size(); ++j) {
ptrToInfoBoard->addPlayer(*static_cast<PlayerInfo *>(PlayersVector[j]));
}
std::ostringstream he;
std::vector<std::string>*ptr = GameBoard::getMapFileNames(DEVCPP_PATH);
for (unsigned int i = 0; i < ptr->size(); ++i) {
he<<DEVCPP_PATH<<ptr->operator[](i);
for (int j = 0; j < EATCH_MAP_PLAY_TIMES; ++j) {
MainGameObject=new GameBoard(true,he.str().c_str(),PlayersVector,EXETASI_MODE,ptrToInfoBoard);
MainGameObject->StartGame();
delete(MainGameObject);
getchar();
}
he.str("");
}
while(1); }
Player.h code :
#ifndef GHOST_PLAYER_H
#define GHOST_PLAYER_H
#include <iostream>
#include <windows.h>
class Player{
private:
public:
Player(){}
virtual std::string getName()=0 ;
virtual std::string getId()=0 ;
virtual int getMove(const char **ViewAround)=0;
virtual void init(int width,int height,int CurrentX,int CurrentY )=0;
};
#endif //GHOST_PLAYER_H
When i am putting at main the
*new FancyPlayer(), 'A')) i am getting an error that telling "[Error] invalid new-expression of abstract class type 'FancyPlayer'" , if i put this line in comment the code works properly...
the stupidplayer code :
StupidPlayer.h :
#ifndef GHOST_STUPIDPLAYER_H
#define GHOST_STUPIDPLAYER_H
#include "../Player/Player.h"
#include "../Move.h"
class StupidPlayer: public Player {
int getMove(const char **ViewAround);
void init(int width,int height,int x,int y);
std::string getName();
std::string getId();
};
#endif //GHOST_STUPIDPLAYER_H
StupidPlayer.cpp :
#include <cstdlib>
#include "StupidPlayer.h"
#include <fstream>
int StupidPlayer::getMove(const char **ViewAround) {
std::ofstream he("inner.txt");
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
he<<ViewAround[i][j];
}
he<<'\n';
}
return STAND;
}
void StupidPlayer::init(int width, int height, int x, int y) {
}
std::string StupidPlayer::getName() {
return std::string("StupidPlayer");
}
std::string StupidPlayer::getId() {
return std::string("cs161119");
}
i cant see any difference between stupidplayer and fancy... what can i do... in order to make fancy works properly... it may be a problem that have 2 classes in use for fancy?

Function does not take 1 arguments when passing this into it

I'm trying to pass an instance of this (the instance in question being the GameEngine class) into my PlayerBrain.run method which takes a GameEngine * const argument corresponding to what this is. I'm curious as to what would cause such an error to be thrown in this case, especially when there are no alternative function definitions for run() or anything like that. PlayerBrain is its own class, not descending from anything. So there's no alternative definitions to run that might cause problems. Here's the relevant code:
All public methods in PlayerBrain.h
#pragma once
#include "GameEngine.h"
#include "Species.h"
#include "Neuron.h"
#include "Genome.h"
#include "GenePool.h"
#include "Gene.h"
#include <sys/stat.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;
class PlayerBrain {
private:
int popSize;
int stalenessThreshold;
int timeoutConstant;
int currentTimeout;
int maxNodes;
int farthestDistance;
bool buttons[6]; // JASON - shoot, left, right, up, down, jump in that order
GenePool p;
bool fileExists(string filename);
bool fitnessAlreadyMeasured();
void nextGenome();
void evaluateCurrent(Genome * g);
void evaluateNetwork(vector<Neuron*> * network, vector<int> inputs);
void loadPool(string filename);
double sigmoid(double sum);
vector<int> getInputs();
Genome templateGenome();
void pressAKey();
void unPressAKey();
vector<INPUT *> oldbuttons;
public:
PlayerBrain();
void intialize();
void run(GameEngine const *);
void close();
};
The actual implementation in its .cpp
void PlayerBrain::run(GameEngine const * g) {
Genome * current = p.getCurrentGenome();
int xPos = 0;
int bossLives = 0;
double fitness;
double timeoutBonus;
unPressAKey();
if ((p.getCurrentFrame() % 5) == 0)
evaluateCurrent(current);
pressAKey();
xPos = g->getXPosAckVar();
bossLives = g->getBossLivesAckVar();
if (xPos > farthestDistance) { farthestDistance = xPos; currentTimeout = timeoutConstant; }
currentTimeout--;
timeoutBonus = p.getCurrentFrame() / 4;
if ((currentTimeout + timeoutBonus) <= 0) {
fitness = (farthestDistance - (p.getCurrentFrame() / 2)) + 2000 * bossLives;
if (fitness == 0) { fitness = -1; }
current->setFitness(fitness);
if (fitness > p.getMaxFitness()) { p.setMaxFitness(fitness); }
p.setCurrentSpecies(0);
p.setCurrentGenome(0);
while (fitnessAlreadyMeasured()) { nextGenome(); }
}
p.setCurrentFrame(p.getCurrentFrame() + 1);
}
The function call in GameEngine.cpp`
while (true)
{
......//irrelevant stuff
if (tickTimeNow > tickTimeTrigger)
{
if (dTimeTrigger > m_PaintTimeTrigger)
{
....
brain->run(this);
....
}
else Sleep(1);
}
else WaitMessage();
}
}
The error I get is as follows:
Error C2660 'PlayerBrain::run': function does not take 1 arguments

Passing Pointers to Classes in C++

I am trying to pass a pointer into my classes function, have it incremented, and have the variable retain it's value using pointers. Heres my code, it doesnt increment.
#include "stdafx.h"
#include <iostream>
using namespace std;
class test
{
public:
int addTo();
test(int * currentY);
private:
int y;
};
test::test(int * currentY):
y(*currentY)
{
}
int test::addTo()
{
y++;
return 0;
}
int main ()
{
for (;;)
{
int pointedAt = 1;
int * number = &pointedAt;
test t(number);
t.addTo();
cout <<*number;
char f;
cin >>f;
}
}
This should do it:
#include "stdafx.h"
#include <iostream>
using namespace std;
class test
{
public:
int addTo();
test(int * currentY);
private:
int *y;
};
test::test(int *currentY):
y(currentY)
{}
int test::addTo()
{
++*y;
return 0;
}
int main ()
{
for (;;)
{
int pointedAt = 1;
test t(&pointedAt);
t.addTo();
cout << pointedAt;
}
}
You have to store a pointer to the integer, so it refers to the same address as the original variable.