Hi,
I have written a code for Roman Numeral basic mathematical operation in C++. How to do unit testing for it/ How to write unit testing program for it?

Here is the code:

``````#include <iostream>
#include <string>

using namespace std;

//Function to convert decimal number to roman
string decimal_to_Roman(int number)
{
string roman = "";
while (number > 0)
{
if (number >= 1000)
{
roman += "M";
number -= 1000;
}
else if (number >= 500)
{
roman += "D";
number -= 500;
}
else if (number >= 100)
{
roman += "C";
number -= 100;
}
else if (number >= 50)
{
roman += "L";
number -= 50;
}
else if (number >= 10)
{
roman += "X";
number -= 10;
}
else if (number >= 5)
{
roman += "V";
number -= 5;
}
else
{
roman += "I";
number -= 1;
}
}
return roman;
}

//Function to convert roman number to decimal
int roman_to_decimal(string roman)
{
int number = 0;
for (int i = 0; i<roman.length(); i++)
{
switch (roman[i])
{
case 'M':
number += 1000;
break;
case 'D':
number += 500;
break;
case 'C':
number += 100;
break;
case 'L':
number += 50;
break;
case 'X':
number += 10;
break;
case 'V':
number += 5;
break;
case 'I':
number += 1;
break;
default:
cout << "Data error\n";
}
}
return number;
}

//Function to perform mathematical operations(+,-,*,/)
int calculator(int n1, int n2, char opr)
{
switch (opr)
{
case '+':
return n1 + n2;
break;
case '-':
return n1 - n2;
break;
case '*':
return n1*n2;
break;
case '/':
if (n2 != 0)
{
return n1 / n2;
}
else
break;
}
return 0;
}

//Function to print result
void result(string r1, string r2, char opr, string r)
{
cout << r1 << endl;
cout << opr << endl;
cout << r2 << endl;
cout << r << endl;
}

int main()
{
string r1, r2, r;
char opr;
int n1, n2, n;
cin >> r1;
n1 = roman_to_decimal(r1);
cin >> opr;
cin >> r2;
n2 = roman_to_decimal(r2);
n = calculator(n1, n2, opr);
r = decimal_to_Roman(n);
result(r1, r2, opr, r);
}``````

## All 4 Replies

If you don't have a unit testing framework at hand, you could use some simple asserts for now, I guess. It might depend on what IDE you use too, because, for example, I have been using Visual Studio's unit testing 'framework' for some time now and it's pretty elegant. As I said, without knowing exactly what IDE, compiler, OS you're using, can't recommend much more than writing some asserts.

System Config- windows 10 32 bit
I coded it on online ide

Today i installed Visual Studio to compile it offline, but there is some configuration problem and not able to run the program

commented: I don't think so!??? +0

Ditto what Coller said. Or even forget the asserts for now. Just run the program for some obvious tests. IV seems to return 6 instead of 4.

When it passes all the obvious stuff you can throw at it, then worry about Unit Testing IMO.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.