2015-02-23 105 views
2

我正在爲幾個返回HTTP響應代碼的方法編寫單元測試。我無法找到斷言HTTP響應代碼的方法。也許我錯過了一些明顯的東西,或者我誤解了PHPUnit的一些東西。驗證PHPUnit中的HTTP響應代碼

我正在使用PHPUnit 4.5 stable。類消息的

相關部分:

public function validate() { 
    // Decode JSON to array. 
    if (!$json = json_decode($this->read(), TRUE)) {  
    return http_response_code(415); 
    } 
    return $json; 
} 

// Abstracted file_get_contents a bit to facilitate unit testing. 
public $_file_input = 'php://input'; 

public function read() { 
    return file_get_contents($this->_file_input); 
} 

單元測試:

// Load invalid JSON file and verify that validate() fails. 
public function testValidateWhenInvalid() { 
    $stub1 = $this->getMockForAbstractClass('Message'); 
    $path = __DIR__ . '/testDataMalformed.json'; 
    $stub1->_file_input = $path; 
    $result = $stub1->validate(); 
    // At this point, we have decoded the JSON file inside validate() and have expected it to fail. 
    // Validate that the return value from HTTP 415. 
    $this->assertEquals('415', $result); 
} 

PHPUnit的回報:

1) MessageTest::testValidateWhenInvalid 
Failed asserting that 'true' matches expected '415'. 

我不確定爲什麼$結果返回 '真'。 。 。特別是作爲一個字符串值。也不確定我的'預期'論據應該是什麼。

+1

如果這個方法返回的代碼,那麼就不會'的assertEquals()'做的工作? – Crackertastic 2015-02-23 19:20:01

+1

你能提供課堂和測試嗎? – 2015-02-23 19:20:25

+0

@Crackertastic我不確定在assertEquals()中使用什麼作爲期望的參數,因爲我從http_response_code()返回的返回值是'true'作爲字符串: - | – sheldonkreger 2015-02-23 19:36:19

回答

2

​​您可以調用不帶參數的http_response_code()方法來接收當前的響應代碼。

<?php 

http_response_code(401); 
echo http_response_code(); //Output: 401 

?> 

因此您的測試應該是這樣的:

public function testValidateWhenInvalid() { 
    $stub1 = $this->getMockForAbstractClass('Message'); 
    $path = __DIR__ . '/testDataMalformed.json'; 
    $stub1->_file_input = $path; 
    $result = $stub1->validate(); 
    // At this point, we have decoded the JSON file inside validate() and have expected it to fail. 
    // Validate that the return value from HTTP 415. 
    $this->assertEquals(415, http_response_code()); //Note you will get an int for the return value, not a string 
} 
+0

完美!我從測試中刪除了$結果,因爲它不是必需的。偉大的思想! – sheldonkreger 2015-02-23 19:49:49

+1

沒問題!樂於幫助。 – Crackertastic 2015-02-23 19:50:43

相關問題