php 使用 PHPUnit 测试数组是否包含值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31638220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
test if array contains value using PHPUnit
提问by Donoven Rally
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
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:
但我的问题是,有没有比我做的更好的断言或其他方法来检查这件事?我尝试使用,assertArrayHasKey
但出现以下错误:
PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertArrayHasKey() must be a integer or string
any idea please? thx
有什么想法吗?谢谢
回答by user2182349
Try the assertContains method:
尝试 assertContains 方法:
$this->assertContains( $randad, $adUnitArr );