vierge-noire / cakephp-fixture-factories

CakePHP Fixture Factories
https://vierge-noire.github.io/
MIT License
85 stars 20 forks source link

Testing simple method without persisting data #193

Closed Erwane closed 1 year ago

Erwane commented 1 year ago

Hi, How to test this, without persisting data ?

public function canUpdate(IdentityInterface $user, Article $article)
{
    return $user->id == $article->user_id;
}

My first way was to create a PR (https://github.com/vierge-noire/cakephp-fixture-factories/pull/192) to add a method to get entity with primary keys sets.

I known the answer could be something like

$user = UserFactory::make(['id' => 1])->getEntity();
$article = ArticleFactory::make(['user_id' => 1)->getEntity();

But, this is more in the same way of persist writing

$user = UserFactory::make()->getEntity();
$article = ArticleFactory::make()->withUser($user)->{insert good method name to get entiy with linked id}()

Thanks

pabloelcolombiano commented 1 year ago

On the unit test level, you might just want to test it this way:

public function testCanUpdate()
    {
        $userId = rand(1, 100);
        $identityStub = $this->getMockBuilder(IdentityInterface::class)->getMock();
        $identityStub->method('getIdentifier')->willReturn($userId);
        $userId = (string)$identityStub->getIdentifier();
        $article = ArticleFactory::make()->setField('user_id', $userId)->getEntity();
        $this->assertTrue($classUnderTest->canUpdate($identityStub, $article));
    }

On the integration side of testing however, you want to have the entities persisted anyway.

Generally I do not think that involving IDs in the getEntity() method is a good idea, nor necessary.