I was going through the book named "Test-Driven Development By Example" By the author Kent Beck.
I am trying to write a similar function in php but not understanding the steps.
Original function:
Test function:
public void testEquality() {
assertTrue(new Dollar(5).equals(new Dollar(5)));
assertFalse(new Dollar(5).equals(new Dollar(6)));
}
Class function:
public boolean equals(Object object) {
Dollar dollar = (Dollar) object;
return amount == dollar.amount;
}
My code:
Test function:
public function setup() {
$this->dollarFive = new Dollar(5);
}
public function testEquality() {
$this->assertTrue($this->dollarFive->equals(new Dollar(5)));
}
Class Function:
class Dollar
{
public function __construct($amount) {
$this->amount = (int) $amount;
}
public function equals(Dollar $object) {
$this->Object = $object;
return $this->amount == $this->Object;
}
}
While executing the test case i am getting the following error.
Object of class Dollar could not be converted to int
Need some help on this. How can i fix this?
return $this->amount == $this->Object;
$this->amount
is an int, $this->Object
isn't an int. You tried to compare each other, thus you'll get
Object of class Dollar could not be converted to int
You probably mean
return $this->amount == $this->Object->amount;
However, there is also something curious in your class
class Dollar {
public $amount = 0; // <-- forgotten
public function __construct($amount) {
$this->amount = (int) $amount;
}
public function equals(Dollar $object) {
$this->Object = $object; // <--- ?!?
return $this->amount == $this->Object;
}
}
you'll probably want just
public function equals(Dollar $object) {
return $this->amount == $object->amount;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With