测试是否随机排序数组

时间:2013-01-02 21:05:39

标签: sorting phpunit shuffle

我正在使用PHPunit测试我的代码。我的代码有几种排序方法:按名称,年龄,计数和随机。下面是按计数排序的实现和测试。这些都是微不足道的。

class Cloud {
  //...
  public function sort($by_property) {
    usort($this->tags, array($this, "cb_sort_by_{$by_property}"));
    return $this;
  }

  private function cb_sort_by_name($a, $b) {
    $al = strtolower($a->get_name());
    $bl = strtolower($b->get_name());
    if ($al == $bl) {
      return 0;
    }
    return ($al > $bl) ? +1 : -1;
  }

  /**
   * Sort Callback. High to low
   */
  private function cb_sort_by_count($a, $b) {
    $ac = $a->get_count();
    $bc = $b->get_count();
    if ($ac == $bc) {
      return 0;
    }
    return ($ac < $bc) ? +1 : -1;
  }
}

经过测试:

  /**
   * Sort by count. Highest count first.
   */
  public function testSortByCount() {
    //Jane->count: 200, Blackbeard->count: 100
    //jane and blackbeard are mocked "Tags".
    $this->tags = array($this->jane, $this->blackbeard);

    $expected_order = array("jane", "blackbeard");
    $given_order = array();

    $this->object->sort("count");

    foreach($this->object->get_tags() as $tag) {
      $given_order[] = $tag->get_name();
    }

    $this->assertSame($given_order, $expected_order);
  }

但是现在,我想添加&#34;随机排序&#34;

  /**
   * Sort random.
   */
  public function testSortRandom() {
    //what to test? That "shuffle" got called? That the resulting array
    // has "any" ordering?
  }

实现可以是从shuffle($this->tags)调用到随机返回0,-1或+1的usort回调。性能是一个问题,但可测试性更重要。

如何测试数组随机排序? AFAIK很难对诸如shuffle之类的全局方法进行存根。

3 个答案:

答案 0 :(得分:1)

假设您使用shuffle,您的方法应如下所示

sortRandom() {
 return shuffle($this->tags);
}

好吧,你不需要测试密钥是否被洗牌但是仍然返回了数组。

function testSortRandom(){
    $this->assertTrue(is_array($this->object->sortRandom()));
}

你应该测试你的代码,而不是php核心代码。

答案 1 :(得分:0)

实际上,这在任何有意义的意义上都是不可能的。如果你有一个只包含几个项目的列表,那么完全有可能通过随机排序确实看起来像是按任何给定字段排序(并且它发生的几率与排序的顺序相同)如果你没有太多的元素,任何其他领域都很高)

如果你问我操作是否实际上没有以任何方式操纵数据,单元测试排序操作似乎有点愚蠢。感觉就像单元测试一样,而不是因为它实际上是在测量某些东西是否符合预期。

答案 2 :(得分:0)

我决定用全局包装器来实现它:

class GlobalWrapper {
  public function shuffle(&$array);
    shuffle($array);
  }
}

在排序中,我通过该包装器调用shuffle

public function sort($by_property) {
  if ($by_property == "random") {
    $this->global_wrapper()->shuffle($this->tags);
  }
  //...
}

然后,在测试中我可以模拟GlobalWrapper并为感兴趣的全局函数提供存根。在这种情况下,我感兴趣的是,方法被调用,而不是它输出[1]。

 public function testSortRandomUsesShuffle() {
   $global = $this->getMock("GlobalWrapper", array("shuffle"));
   $drupal->expects($this->once())
     ->method("shuffle");
   $this->object->set_global_wrapper($drupal);

   $this->object->sort("random");
 }

[1]实际上我也有这个包装器的单元测试,测试参数以及它执行call-by-ref的事实。此外,这个包装器已经实现(并称为DrupalWrapper),以允许我存根由第三方(Drupal)提供的某些全局功能。这个实现允许我使用set_drupal()传递包装器并使用drupal()获取它。在上面的示例中,我将这些称为set_global_wrapper()global_wrapper()