使用PHPUnit测试数组是否包含值

使用PHPUnit测试数组是否包含值

本文介绍了使用PHPUnit测试数组是否包含值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个对象数组:

I created this array of objects:

$ad_1 = new AdUnit(array('id' => '1', 'name' => 'Ad_1', 'description' => 'great ad', 'code' => 'alpha', 'widget_id' => '123'));
$ad_2 = new AdUnit(array('id' => '2', 'name' => 'Ad_2', 'description' => 'good ad', 'code' => 'delta', 'widget_id' => '456'));
$ad_3 = new AdUnit(array('id' => '3', 'name' => 'Ad_3', 'description' => 'bad ad', 'code' => 'sigma', 'widget_id' => '789'));
$adUnitArr = array($ad_1, $ad_2, $ad_3);

,我想检查从函数获得的随机广告是否存在于数组中.获取广告的代码如下:

and i want to check that a random ad i got from a function exists in the array. the code to get the ad looks like this:

        $fixture = new AdGroup();
$fixture->setAds($adUnitArr);
$randad = $fixture->getRandomAd();

现在我要检查数组是否包含我收到的随机广告,我是怎么做到的:

now i want to check if the array contains the random ad i received, what i was able to do like this:

$this->assertEquals(in_array($randad, $adUnitArr), 1); //check if ad in array

但是我的问题是,有没有一个断言或其他方法可以比我做的更好的方式检查这件事?我尝试使用assertArrayHasKey,但出现以下错误:

but my question is, is there an assert or some other way to check this thing better than the way i did it?? i tried using assertArrayHasKey but i got the following error:

PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertArrayHasKey() must be a integer or string

有什么好主意吗?

推荐答案

尝试使用assertContains方法:

Try the assertContains method:

$this->assertContains( $randad, $adUnitArr );

这篇关于使用PHPUnit测试数组是否包含值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 18:34