2012-02-25 25 views
9

我在想如果我可以驗證'class'是否有函數。 assertClassHasAttribute不起作用,這是正常的,因爲函數不是屬性。HowTo PHPUnit assertFunction

+2

你爲什麼要測試? – Gordon 2012-02-25 23:34:33

+0

當我做一些重構時非常有用...必須通過測試知道我的類包含的方法有助於在某些原因需要將方法轉移到另一個類中時:如解耦響應等。 – HexaGridBrain 2012-02-26 02:35:55

+0

我會爭論當你確定依賴關係被正確地模擬/存根,並且你完全覆蓋了你的公共API時,你永遠不需要這個。 – Gordon 2012-02-26 10:51:53

回答

32

當有不PHPUnit的我提供了一個斷言方法可以創建或使用較低級別的斷言一個帶有詳細信息:

$this->assertTrue(
    method_exists($myClass, 'myFunction'), 
    'Class does not have method myFunction' 
); 

assertTrue()是基本的,你可以得到。它允許很大的靈活性,因爲您可以使用任何內置的php函數返回測試的bool值。因此,當測試失敗時,錯誤/失敗消息根本沒有幫助。類似Failed asserting that <FALSE> is TRUE。這就是爲什麼將第二個參數傳遞給assertTrue()以說明測試失敗的原因。

7

單元和集成測試用於測試行爲,不用於重申 類定義。

所以PHPUnit不提供這樣的斷言。 的PHPUnit可以斷言,一個類可以有名稱X,該函數返回值的財產以後,但你可以做你想做使用的是什麼:

/** 
* Assert that a class has a method 
* 
* @param string $class name of the class 
* @param string $method name of the searched method 
* @throws ReflectionException if $class don't exist 
* @throws PHPUnit_Framework_ExpectationFailedException if a method isn't found 
*/ 
function assertMethodExist($class, $method) { 
    $oReflectionClass = new ReflectionClass($class); 
    assertThat("method exist", true, $oReflectionClass->hasMethod($method)); 
} 
+0

真棒。這聽起來非常適合我的需求。謝謝@MounaCheikhna – shan 2015-06-27 18:43:36