vendredi 3 avril 2020

How do I mock the nth invocation of a function in Laravel testing

I have a site that needs to connect occasionally to a secondary database. I've got all that working correctly, but of course I need it testable.

Connections to the second database need to be transactional, so I'd like a test that mimics a failed transaction.

So in my Job I have code similar to the following:

DB::transaction(function() {
  //snip
  DB::connection('conn2')->table('table1')->insert($data);
  $id = DB::connection('conn2')->table('table1')->select('id')->value('id');
  //snip2
  DB::connection('conn2')->table('table2')->insert($data2);
});

I want a test case that causes the final query to fail (e.g. an exception thrown at snip2) so that I can confirm that the entire transaction was rolled back (i.e. $data is not found in table1).

Is there a way to mock my Connection object such that every other command executes normally and hits the testing Sqlite database, but table('table2') fails?

Aucun commentaire:

Enregistrer un commentaire