Improve test_constructor, add custom error

This commit is contained in:
Tobias Berger 2021-09-21 10:42:04 +02:00
parent 854e87e616
commit 912644d841
3 changed files with 19 additions and 5 deletions

View file

@ -40,7 +40,7 @@ namespace FractionNS {
Fraction::Fraction(int numerator, int denominator)
{
if(denominator == 0) throw std::range_error("Tried to divide by 0.");
if(denominator == 0) throw divide_by_zero_error();
this->m_numerator = numerator;
this->m_denominator = denominator;
reduce();
@ -62,7 +62,7 @@ namespace FractionNS {
this->m_numerator = numerator / gcd;
}
void Fraction::setDenominator(int denominator) {
if(denominator == 0) throw std::range_error("Tried to divide by 0.");
if(denominator == 0) throw divide_by_zero_error();
auto gcd = FractionNS::gcd(this->m_numerator, denominator);
this->m_denominator = denominator / gcd;
}

View file

@ -3,6 +3,11 @@
#include <QString>
namespace FractionNS {
class divide_by_zero_error : public std::logic_error {
public:
divide_by_zero_error() : std::logic_error("tried to divide by zero") {};
};
class Fraction
{
private:

View file

@ -60,11 +60,20 @@ void FractionTest::test_constructor() {
// Zero
Fraction f6 = Fraction(0);
QCOMPARE(f6, 0);
QCOMPARE(f6.getNumerator(), 0);
Fraction f7 = Fraction(0, 3);
QCOMPARE(f7, 0);
QCOMPARE(f7.getNumerator(), 0);
QCOMPARE(f6, f7);
QCOMPARE(f6.getDenominator(), f7.getDenominator());
// Invalid zero fraction
bool threw_divide_by_zero_error = false;
try {
Fraction(2, 0);
} catch (const divide_by_zero_error&) {
threw_divide_by_zero_error = true;
}
QVERIFY(threw_divide_by_zero_error);
}
void FractionTest::test_display() {