2013-02-26 87 views
3

现在我正在玩PHPUnit的日子。我已经通过它的文档,但我无法理解它。让我解释我的情况。为返回数组的函数编写PHPUnit测试

我有一个功能,需要三个参数1 array, 2 some string, 3 a class object。 此函数通过将第二个参数作为数组的索引并将结果作为该索引的对象返回数组。我的功能如下

public function construct($testArray, $test,$analysisResult) { 
    $postedTest = explode('_', $test); 
    $testName = end($postedTest); 
    $postedTest = implode("_", array_slice($postedTest, 0, -1)); 
    if (in_array($postedTest, array_keys($testArray))) { 
     $testArray[$postedTest][$testName] = $analysisResult; 
    } else { 
     $testArray[$postedTest] = array($testName => $analysisResult); 
    } 
    return $testArray; 
} 

如果我把喜欢

$constructObj = new Application_Model_ConstructTree(); 
    $test=$this->getMockForAbstractClass('Abstract_Result'); 
    $test->level = "Error"; 
    $test->infoText = "Not Immplemented"; 
    $testArray = Array('databaseschema' => Array('Database' => $test)); 

    $result = $constructObj->construct($testArray,"Database",$test); 

函数这个函数返回像

Array 
(
[databaseschema] => Array 
    (
     [Database] => AnalysisResult Object 
      (
       [isRepairable] => 1 
       [level] => Error 
       [infoText] => Not Implemented 
      ) 

    ) 
) 

数组现在我想写一个PHPUnit的测试,以检查像isRepairable, level and infoText这样的对象的属性存在而不是空的。我有一个想法,assertNotEmptyassertAttributeEmpty可以做一些事情但我无法理解如何做到这一点。

我的测试看起来像

public function testcontruct() { 
    $constructObj = new Application_Model_ConstructTree(); 
    $test=$this->getMockForAbstractClass('Abstract_Result'); 
    $test->level = "Error"; 
    $test->infoText = "Not Immplemented"; 
    $testArray = Array('databaseschema' => Array('Database' => $test)); 

    $result = $constructObj->construct($testArray,"Database",$test); 

    $this->assertNotCount(0, $result); 
    $this->assertNotContains('databaseschema', $result); 
} 

任何人都可以请指导:-)

+0

它看起来像你的问题可能Ĵ最好与断言。这些发生在失败时。因此,当条件不成立时,assertTrue(Condition)实际上只会通过断言(错误)。断言仅在失败时发生,所以就好像他们错过了'只有当结果不是'名字'时。 – 2013-02-26 15:41:27

回答

5

最后一行应改为assertContainsassertNotContains。在测试的下一步将是:

$this->assertContains('Database', $result['databaseschema']); 
$this->assertAttributeNotEmpty('isRepairable', $result['databaseschema']['Database']); 
$this->assertAttributeNotEmpty('level', $result['databaseschema']['Database']); 
$this->assertAttributeNotEmpty('infoText', $result['databaseschema']['Database']); 

assertAttributeNotEmpty需要的属性名称和对象作为参数,就像assertContains采取数组键和阵列。

+0

谢谢老兄。很好解释 – 2013-02-26 12:25:28