nelmio / alice

Expressive fixtures generator
MIT License
2.5k stars 329 forks source link

Usage without a property setter (private property)? #1130

Closed gremo closed 1 year ago

gremo commented 1 year ago

I'll usually omit setters to not be able to change, even by mistaker, something that should be computed. For example, take a cart: I don't expose setTotalAmount because should and must be calculated when adding/removing items only.

And this, of course, will fail because the property accessor can't find a setter for the property:

App\Entity\Cart:
    cart{1..10}:
      totalAmount: <randomFloat(2, 0, 10000)>

How do you would solve this common problem?

alexislefebvre commented 1 year ago

I'm not sure to understand why you try to define a value that is not writable.

Does getTotalAmount() compute a sum of items or is it bound to a data in database?

gremo commented 1 year ago

@alexislefebvre sorry for being unclear.

I don't want that property writable because, in fact, it's computed as long as you add items. It returns the private totalAmount property, that is updated as you add/remove items.

But right now, I don't want to generate and add items to the cart. I'd like to test only some functionality here my request: is there a way to set the value without the setter (maybe some reflection option I don't know).

Thanks

alexislefebvre commented 1 year ago

Why try to overwrite a value that is computed? If the cart is empty, totalAmount will be 0.

In other words, why fixtures should do something that is impossible through PHP? Maybe you should use a mock / stub from PHPUnit instead, so that you can change the behaviour of getTotalAmount(), see https://docs.phpunit.de/en/9.5/test-doubles.html#test-doubles-stubs-examples-stubtest-php

gremo commented 1 year ago

I see your point, thank you. I'll go for real fixtues with items (so total amount would be "right") then.

alexislefebvre commented 1 year ago

Yes it makes sense to use 0 and n items and check that getTotalAmount() return the sum of the amounts, if you want to test this method.