To test the Balance class, you can use mocking to ensure that the correct balance class (BlockBalance or LeaseBalance) is being called with the expected parameters. Here's how you can do it using PHPUnit and Mockery (a popular PHP mocking library).
First, make sure you have PHPUnit and Mockery installed. If not, you can install them using Composer:
composer require --dev phpunit/phpunit mockery/mockery
Now, let's write a test for the Balance class:
<?php
use PHPUnit\Framework\TestCase;
use Mockery as m;
use App\Models\Block;
use App\Models\Lease;
class BalanceTest extends TestCase
{
public function tearDown(): void
{
m::close();
}
public function testBalanceForBlockCallsBlockBalanceBetweenMethod()
{
// Arrange
$from = '2021-01-01';
$to = '2021-01-31';
$block = new Block();
$blockBalanceMock = m::mock('overload:App\Balances\BlockBalance');
$blockBalanceMock->shouldReceive('between')
->once()
->with($from, $to)
->andReturn('expected result');
// Act
$balance = new Balance();
$result = $balance->for($block)->between($from, $to);
// Assert
$this->assertEquals('expected result', $result);
}
public function testBalanceForLeaseCallsLeaseBalanceBetweenMethod()
{
// Arrange
$from = '2021-01-01';
$to = '2021-01-31';
$lease = new Lease();
$leaseBalanceMock = m::mock('overload:App\Balances\LeaseBalance');
$leaseBalanceMock->shouldReceive('between')
->once()
->with($from, $to)
->andReturn('expected result');
// Act
$balance = new Balance();
$result = $balance->for($lease)->between($from, $to);
// Assert
$this->assertEquals('expected result', $result);
}
}
In this test, we're using Mockery's overload prefix to mock a class that doesn't exist yet in the context of the test. This allows us to intercept calls to the BlockBalance and LeaseBalance constructors and return our mock objects instead.
The shouldReceive method sets up an expectation that the between method will be called once with the specified parameters. We then assert that the result of calling between on the Balance class is what we expect.
Remember to call m::close() in the tearDown method to clean up the Mockery container for the next test.
With these tests, you're ensuring that the Balance class correctly delegates the between method call to the appropriate balance class with the correct parameters.