pomm-project / ModelManager

Model Manager for the Pomm database framework.
MIT License
66 stars 27 forks source link

Best way to unit test a ModelLayer class #12

Open davincho opened 9 years ago

davincho commented 9 years ago

As already discussed in https://github.com/pomm-project/ModelManager/issues/8, only within a ModelLayer class it is possible to start and commit/rollback transactions, as for instance per definition Model methods should be atomic.

Now talking about PHPUnit, I would like to start in my setUp routine a transaction which will be rollbacked after a test completes to ensure data consistency among all tests.

What is the best way to achieve this? Or should I do something like:

/** @before */
public function setUp() {
  $db->getConnection()->executeAnonymousQuery('begin transaction')
}

/** @after */
public function tearDown() {
  $db->getConnection()->executeAnonymousQuery('rollback transaction')
}

I am using Silex by the way ...

Cheers

chanmix51 commented 9 years ago
per definition Model methods should be atomic.

That's true, so must be one query per model method. The model layer is intended to group several model's method calls into transactions.

Model's methods must be unit tested on their own so the model layer's test can be kept simple.

Why not nesting model's methods in transactions to rollback them after the test, it is a good idea.

tlode commented 9 years ago

I am using begin / rollback in tests in the way you described. But as my ModelLayer classes, which I want to test, use transactions itself, I need the ability that transactions can be nested through the use of savepoints. I achieve this through this trait, which overwrites the default transaction methods in ModelLayer.

But I am also interested in how others doing this. @chanmix51 said using transactions in tests is not a good idea. Instead one should use a separate schema for the tests and drop it afterwards. But since the schema is fixed in RowStructure::setRelation() by the cli model generator, how could this be circumvented?

davincho commented 9 years ago

Thanks @tlode for providing the link to the transcation trait - I am going to use it.

Since I am in the same situation like tlode, nesting of transcations would be really useful - a possible enhancement?