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

时间:2015-07-26 14:37:46

标签: php phpunit

我创建了这个对象数组:

$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);

我想检查一个函数中存在的随机广告是否存在于数组中。获取广告的代码如下所示:

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

现在我想检查数组是否包含我收到的随机广告,我能够做到这一点:

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

但我的问题是,是否有一种断言或其他方式来检查这件事比我做的更好?我尝试使用assertArrayHasKey,但我收到以下错误:

PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertArrayHasKey() must be a integer or string
请问有什么想法吗? THX

1 个答案:

答案 0 :(得分:70)

尝试使用assertContains方法:

Select p.Id [SenderId], 
       p.Username, 
       count(mr.RecipientId) [TotalMessages], 
       count(case when mr.ReadDate is null then 1 end) As [NewMessages],
       up.PhotoId, 
       p.LastLoggedIn, 
       p.LoggedIn
 FROM [User].[User_Profile] p
 JOIN [MailBox].[Message] m on p.Id = m.SenderId
 JOIN [MailBox].[MessageRecipient] mr on m.Id = mr.MessageId
 LEFT JOIN [User].[User_Photos] up on p.Id = up.UserId and up.isProfilePic = 1 
 where mr.RecipientId = @UserId and mr.DeletedDate is null
 GROUP BY p.id, 
          p.Username, 
          mr.RecipientId, 
          up.PhotoId, 
          p.LastLoggedIn, 
          p.LoggedIn