skip to Main Content

I have such result from my code that I am trying to test:

$result = [
   [
      "lable" => "first", ["type" => "customer", "balance" => 1000],
   ],
   [
      "lable" => "another", ["type" => "retailer", "balance" => 1500],
   ],

]

so I want to test my code and assert that is there any item in my result With balance more than 1200.
also, I want To assert that is there any customer type object in the value?

2

Answers


  1. You could use array_reduce() for this:

    $isAboveThreshold = array_reduce($result, function ($carry, $item) {
        return $carry || $item[0]['balance'] > 1200;
    }, false);
    $hasCustomer = array_reduce($result, function ($carry, $item) {
        return $carry || $item[0]['type'] == 'customer';
    }, false);
    
    Login or Signup to reply.
  2. There is no straight way to use a built-in function, You can do something like this:

    class MyTest extends PHPUnitFrameworkTestCase
    {
        public function testResultHasBalanceGreaterThan1200()
        {
            $result = [
                [
                    "label" => "first", ["type" => "customer", "balance" => 1000],
                ],
                [
                    "label" => "another", ["type" => "retailer", "balance" => 1500],
                ],
            ];
    
            $hasBalanceGreaterThan1200 = false;
    
            foreach ($result as $item) {
                if (isset($item[1]['balance']) && $item[1]['balance'] > 1200) {
                    $hasBalanceGreaterThan1200 = true;
                    break;
                }
            }
    
            $this->assertTrue($hasBalanceGreaterThan1200);
        }
    
        public function testResultHasCustomerTypeObject()
        {
            $result = [
                [
                    "label" => "first", ["type" => "customer", "balance" => 1000],
                ],
                [
                    "label" => "another", ["type" => "retailer", "balance" => 1500],
                ],
            ];
    
            $hasCustomerTypeObject = false;
    
            foreach ($result as $item) {
                if (isset($item[1]['type']) && $item[1]['type'] === 'customer') {
                    $hasCustomerTypeObject = true;
                    break;
                }
            }
    
            $this->assertTrue($hasCustomerTypeObject);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search