5 * This is an example of a barebones test which uses a transaction (based on CiviTestListener).
7 * We check that the transaction works by creating some example records in setUp(). These
8 * records should fetchable while the test executes, but not during tearDownAfterClass().
12 class ExampleTransactionalTest
extends \PHPUnit\Framework\TestCase
implements HeadlessInterface
, TransactionalInterface
{
18 protected static $contactIds = [];
20 public function setUpHeadless() {
21 return \Civi\Test
::headless()->apply();
24 protected function setUp() {
25 /** @var \CRM_Contact_DAO_Contact $contact */
26 $contact = \CRM_Core_DAO
::createTestObject('CRM_Contact_DAO_Contact', [
27 'contact_type' => 'Individual',
29 self
::$contactIds[$this->getName()] = $contact->id
;
33 * In the first test, we make make testDummy1. He exists.
35 public function testDummy1() {
36 $this->assertTrue(is_numeric(self
::$contactIds['testDummy1']) && self
::$contactIds['testDummy1'] > 0);
38 // Still inside transaction. Data exists.
39 $dao = new \
CRM_Contact_DAO_Contact();
40 $dao->id
= self
::$contactIds['testDummy1'];
41 $this->assertTrue((bool) $dao->find());
45 * We previously made testDummy1, but he's been lost (rolled-back).
46 * However, testDummy2 now exists.
48 public function testDummy2() {
49 $this->assertTrue(is_numeric(self
::$contactIds['testDummy1']) && self
::$contactIds['testDummy1'] > 0);
50 $this->assertTrue(is_numeric(self
::$contactIds['testDummy2']) && self
::$contactIds['testDummy2'] > 0);
52 // Previous contact no longer exists
53 $dao = new \
CRM_Contact_DAO_Contact();
54 $dao->id
= self
::$contactIds['testDummy1'];
55 $this->assertFalse((bool) $dao->find());
57 // Still inside transaction. Data exists.
58 $dao = new \
CRM_Contact_DAO_Contact();
59 $dao->id
= self
::$contactIds['testDummy2'];
60 $this->assertTrue((bool) $dao->find());
63 public function tearDown() {
67 * Both testDummy1 and testDummy2 have been created at some point (as part of the test runs),
68 * but all the data was rolled-back
72 public static function tearDownAfterClass() {
73 if (!is_numeric(self
::$contactIds['testDummy1'])) {
74 throw new \
Exception("Uh oh! The static \$contactIds does not include testDummy1! Did the test fail to execute?");
77 if (!is_numeric(self
::$contactIds['testDummy2'])) {
78 throw new \
Exception("Uh oh! The static \$contactIds does not include testDummy2! Did the test fail to execute?");
81 $dao = new \
CRM_Contact_DAO_Contact();
82 $dao->id
= self
::$contactIds['testDummy1'];
84 throw new \
Exception("Uh oh! testDummy1 still exists!");
87 $dao = new \
CRM_Contact_DAO_Contact();
88 $dao->id
= self
::$contactIds['testDummy2'];
90 throw new \
Exception("Uh oh! testDummy2 still exists!");