Skip to content
This repository was archived by the owner on Nov 13, 2018. It is now read-only.

Commit e7a4756

Browse files
peter279kankurk91
authored andcommitted
Improve the divideTwo method and code coverage (#2)
* detect the divisor number is zero, divide testing * replace the string with InvalidArgumentException * Remove Todo
1 parent 7079d97 commit e7a4756

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

app/Classes/Calculator.php

+4-2
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@ public function subtractTwo($x, $y)
5252
}
5353

5454
/**
55-
* Divide two numbers
56-
* //todo Handle divide by zero.
55+
* Divide two numbers.
5756
*
5857
* @param $x
5958
* @param $y
@@ -62,6 +61,9 @@ public function subtractTwo($x, $y)
6261
*/
6362
public function divideTwo($x, $y)
6463
{
64+
if($y === 0) {
65+
throw new \InvalidArgumentException("The divisor cannot be zero!");
66+
}
6567
return $x / $y;
6668
}
6769
}

tests/CalculatorTest.php

+24-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
namespace Tests;
44

55
use PHPUnit\Framework\TestCase;
6-
use Projects\Ankur as App;
6+
use Projects\Ankur\Calculator;
77

88
/**
99
* Class CalculatorTest.
@@ -13,16 +13,22 @@ class CalculatorTest extends TestCase
1313
/**
1414
* Calculator class instance
1515
*
16-
* @var App\Calculator
16+
* @var Projects\Ankur\Calculator
1717
*/
1818
private $calc;
1919

2020
public function __construct()
2121
{
22-
$this->calc = new App\Calculator();
22+
$this->calc = new Calculator();
2323
parent::__construct();
2424
}
2525

26+
public function testInstanceCalculator()
27+
{
28+
$this->calc = new Calculator();
29+
$this->assertInstanceOf(Calculator::class, $this->calc);
30+
}
31+
2632
public function testAdd()
2733
{
2834
fwrite(STDOUT, __METHOD__ . "\n");
@@ -47,5 +53,19 @@ public function testSubtract()
4753
$this->assertEquals($value, 2);
4854
}
4955

50-
// Left divide function intentionally
56+
public function testNormalDivide()
57+
{
58+
fwrite(STDOUT, __METHOD__ . "\n");
59+
60+
$value = $this->calc->divideTwo(4, 2);
61+
$this->assertEquals($value, 2);
62+
}
63+
64+
public function testDivisorHasZero()
65+
{
66+
fwrite(STDOUT, __METHOD__ . "\n");
67+
68+
$this->expectException(\InvalidArgumentException::class);
69+
$value = $this->calc->divideTwo(4, 0);
70+
}
5171
}

0 commit comments

Comments
 (0)