Depends Annotation

The @depends annotation helps you to define some dependencies between methods.

Format

1
2
3
/**
 * @depends methodName
 */

Please note that dependencies don’t define the order in which the test methods are executed, so you still have to keep to proper order for your methods.

Example 1

Let’s check the following basic example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * @return int
 */
public function testOne(): int
{
    $number = 2;
    $this->assertEquals(2, $number);

    return $number;
}

/**
 * @depends testOne
 *
 * @param $number
 */
public function testNumber($number)
{
    $this->assertEquals(2, $number);
}

Example 2

If using multiple dependencies, arguments are passed in the annotations’ defined order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * @return int
 */
public function testTwo(): int
{
    $number = 2;
    $this->assertEquals(2, $number);

    return $number;
}

/**
 * @return int
 */
public function testOne(): int
{
    $number = 1;
    $this->assertEquals(1, $number);

    return $number;
}

/**
 * @depends testOne
 * @depends testTwo
 *
 * @param $one
 * @param $two
 */
public function testNumber(int $one, int $two)
{
    $this->assertEquals(1, $one);
    $this->assertEquals(2, $two);
}

Example 3

Let’s check the following practical example, where we’ll be checking the customer email by customer ID.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\TestFramework\Helper\Bootstrap;
...

/**
 * @magentoDataFixture Magento/Customer/_files/customer.php
 */
public function testLoadCustomer(): CustomerInterface
{
    $customerId = 1;
    $objectManager = Bootstrap::getObjectManager();
    $customerRepository = $objectManager->create(CustomerRepositoryInterface::class);

    return $customerRepository->getById($customerId);
}

/**
 * @depends testLoadCustomer
 *
 * @param CustomerInterface $customer
 */
public function testEmail(CustomerInterface $customer)
{
    $this->assertEquals('customer@example.com', $customer->getEmail());
}

You can read more about PHPUnit dependency annotation here.