I'm writing a test for a class that creates a new version of itself and inserts it into the database. The insert method returns an id which I want to record against the original class a bit like this.
class Invoice {
public function creditInvoice() {
$credit = new static();
// ....
$creditId = $credit->insert();
$this->credited_by = $creditId;
$this->update();
return $credit;
}
}
My test mocks the Invoice class and replaces update and insert. It then replaces insert with a function to return an id.
class InvoiceTest {
public function testCreditInvoice {
$invoice = $this->getMock('Invoice', array('update', 'insert'));
$invoice->expects($this->any())
->method('insert')
->will($this->returnValue(1234));
$credit = $invoice->creditInvoice();
$this->assertTrue(
$invoice->credited_by == 1234
);
}
}
This fails. It seems that although the new static()
correctly makes a new version of the mock class, it doesn't bring the overridden method with it, so credited_by
is actually null.
The only suggestion I've seen that would solve this is to create a new test class, that inherits Invoice but overrides the insert function to return my test data but this doesn't seem like good practice to me.
Is there a better way?