【发布时间】:2015-02-26 08:08:57
【问题描述】:
我需要有关 PHPUnit 和一些方法的帮助。你们应该如何在 PHPUnit 中编写测试以达到以下属性和方法的高代码覆盖率?
我对 PHPUnit 还很陌生,可能需要一些帮助。我刚刚为更基本的代码编写了一些测试用例。此类为最终用户生成 Flash 消息,并将其存储在会话中。
非常感谢您的帮助。有什么想法吗?
private $sessionKey = 'statusMessage';
private $messageTypes = ['info', 'error', 'success', 'warning']; // Message types.
private $session = null;
private $all = null;
public function __construct() {
if(isset($_SESSION[$this->sessionKey])) {
$this->fetch();
}
}
public function fetch() {
$this->all = $_SESSION[$this->sessionKey];
}
public function add($type = 'debug', $message) {
$statusMessage = ['type' => $type, 'message' => $message];
if (is_null($this->all)) {
$this->all = array();
}
array_push($this->all, $statusMessage);
$_SESSION[$this->sessionKey] = $this->all;
}
public function clear() {
$_SESSION[$this->sessionKey] = null;
$this->all = null;
}
public function html() {
$html = null;
if(is_null($this->all))
return $html;
foreach ($this->all as $message) {
$type = $message['type'];
$message = $message['message'];
$html .= "<div class='message-" . $type . "'>" . $message . "</div>";
}
$this->clear();
return $html;
}
我已经设置了一个设置案例,如下所示:
protected function setUp() {
$this->flash = new ClassName();
}
还尝试了一个测试用例:
public function testFetch() {
$this->assertEquals($this->flash->fetch(), "statusMessage", "Wrong session key.");
}
但收到一条错误消息告诉我:“未定义变量:_SESSION” 如果我再尝试:
public function testFetch() {
$_SESSION = array();
$this->assertEquals($this->flash->fetch(), "statusMessage", "Wrong session key.");
}
我收到另一条错误消息:“未定义索引:状态消息”
【问题讨论】:
-
1.将所有装饰 (html) 移出此代码 2. 将您的闪存消息存储与其他逻辑分开。 3.????????? 4. 利润!!!1111
-
我无法更改此代码。需要像现在一样对其进行测试。你知道怎么做吗?请帮忙。 :)
-
试试这样的:
function testWithoutSessionKey() { $_SESSION = array(); $yourClass = new YourclassName(); $this->assertNull($yourClass->html()); } function testWithSomeSessionKey() { $_SESSION = array( 'statusMessage' => array(...)); $yourClass = new YourclassName(); $this->assertSame($expect, $yourClass->html()); }希望对你有帮助 -
@Matteo:
testWithoutSessionKey()工作正常。 :) 你能用你将如何测试这些方法的信息来回答这个问题吗?请! :) 我已经更新了问题。 -
你在路上!您在代码中发现了一个错误!现在您可以修复它(您必须在访问它之前检查已设置密钥的 fetch 方法)。我想第二种方法很好。我应该只发布您在答案中输入的代码
标签: php class unit-testing methods phpunit