Reputation: 51
I have a class Receipt.php that I need to PHPUnit test.
<?php
namespace TDD;
class Receipt {
public $user_id = 1;
private $pending_amount = 45;
public function total(array $items = []){
$this->pending();
$items[] = $this->pending_amount;
return array_sum($items);
}
public function tax($amount,$tax){
return $amount * $tax;
}
private function pending()
{
$sql = 'select pending_amount from Pending_transtions where user_id =' . $this->user_id . ' limit 1;';
//$pending_amt = $this->mainDb->get_sql_row($sql);
//$this->pending = $pending_amt['pending_amount'];
$this->pending_amount = 55;
}
public function addTaxPending($tax){
return $this->pending_amount * $tax;
}
}
?>
In PHPUnit test file ReceiptTest.php
<?php
namespace TDD\Test;
require(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php';
use PHPUnit\Framework\TestCase; // its imoprt core class
use TDD\Receipt; //its load our receipt class
class ReceiptTest extends TestCase{
public function setUp(): void {
$this->Receipt = new Receipt('s','p');
}
public function tearDown(): void{
unset($this->Receipt);
}
public function testTotal(){
$input = [0,2,5,8];
$output = $this->Receipt->total($input);
$this->assertEquals(60,$output,"this is not valid");
}
public function testTax(){
$inputAmount = 10.00;
$inputTax = 0.10;
$output = $this->Receipt->tax($inputAmount,$inputTax);
$this->assertEquals(1.0,$output,"this tax expecting 1.0");
}
}
?>
I want to avoid $this->pending(); internal calling function at function total() in Receipt class. But I need to access of property pending_amount.
Here my challenges are pending_amount private property. How can I handle that?
How can skip pending function and how to access pending_amount property on PHPUnit file?
I also tried this way
public function test_total2(){
$myStubObject = $this
->getMockBuilder(Receipt::class)
->setConstructorArgs(['s','p'])
->setMethods(["pending"])
->getMock();
$myStubObject
->method('pending')
->withAnyParameters()
->willReturn(45);
$input = [0,2,5,8];
$output = $myStubObject->total($input);
$this->assertEquals(60,$output);
}
Its throwing an error like
- TDD\Test\ReceiptTest::test_total2 PHPUnit\Framework\MockObject\MethodCannotBeConfiguredException: Trying to configure method >"pending" which cannot be configured because it does not exist, has not been specified, is final, >or is static
But there is return in Pending function so I need to access pending_amount property. I hope that I clearly explain my problem, If you have any doubts please don't hesitate.
I'll recorrect it. Looking for your valuable inputs
Upvotes: 1
Views: 156