I am writing unit test for manager class which can persist data into database with usage of repository. I want to assert that repository method save() is called with given data. In this case it is Entity object called Instance which has few standard fields and uuid. But when running this test phpunit is telling me that Instance object I've provided in test has different uuid from object that is beeing send as argument in the invoked method. So my problem is that i know where error comes from but i don't have idea how to fix it.
class InstanceManagerTest extends TestCase
{
private InstanceManager $instanceManager;
private CreateInstance $createInstanceDto;
private Instance $instanceEntity;
private MockObject $instanceRepositoryMock;
protected function setUp(): void
{
$this->instanceManager = new InstanceManager(
$this->instanceRepositoryMock = self::createMock(InstanceRepositoryInterface::class)
);
$this->createInstanceDto = new CreateInstance(
new CreateAddress(
'asd',
'asd',
'asd',
'asd',
'asd'
),
'asd',
'asd',
'asd',
'asd'
);
$this->updateInstanceDto = new UpdateInstance(
new UpdateAddress(
'asd',
'asd',
'asd',
'asd',
'asd',
Uuid::v4()
),
'asd',
'asd',
'asd',
'asd',
Uuid::v4()
);
$this->instanceEntity = new Instance(
$this->createInstanceDto->name,
$this->createInstanceDto->nip,
$this->createInstanceDto->regon,
$this->createInstanceDto->krs,
new Address($this->createInstanceDto->address)
);
}
/** @test */
public function create_validArguments_returnsInstancePresenter()
{
// Here I expect that method save() of Instance repository will be called once with same object InstanceEntity
$this->instanceRepositoryMock->expects(
$this->once())->method('save')->with($this->instanceEntity);
$result = $this->instanceManager->create($this->createInstanceDto);
// Assert
self::assertInstanceOf(InstancePresenter::class, $result);
}
}
class InstanceManager
{
public function __construct(private readonly InstanceRepositoryInterface $repository)
{
}
public function create(CreateInstance $dto): InstancePresenter
{
return InstancePresenter::fromEntity($this->repository->save(
// Here when I create Instance it sets all fields form dto except uuid which is beeing generated
new Instance(
$dto->name,
$dto->nip,
$dto->regon,
$dto->krs,
new Address(
$dto->address
)
)
));
}
//...
}
class Instance
{
private readonly ?int $id;
private Uuid $instanceId;
private string $name;
private string $nip;
private string $regon;
private string $krs;
private Address $address;
private ?\DateTimeImmutable $deletedAt = null;
public function __construct(string $name, string $nip, string $regon, string $krs, Address $address)
{
$this->instanceId = Uuid::v4();
$this->update($name, $nip, $regon, $krs, $address);
}
public function update(string $name, string $nip, string $regon, string $krs, Address $address): self
{
$this->name = $name;
$this->nip = $nip;
$this->regon = $regon;
$this->krs = $krs;
$this->address = $address;
return $this;
}
//...
}