Laravel 5.0会话变量单元测试问题



我正在尝试对一些现有代码进行一些单元测试。我的控制器看起来有点像

class DefaultController extends Controller
{
public function index() {
if (!Session::get('answers', [])) {
App::abort(403, 'Error.');
}
// Do rest of the stuff here
}
}

我的测试课看起来有点像

class DefaultController extends extends TestCase {
public function testIndex_withoutSession() {
// Arrange
/* Nothing to arrange now */
// Act
$this->action('GET', 'DefaultController@index');
// Assert
$this->assertResponseStatus(403);
}
public function testIndex_withSession() {
// Arrange
$this->session(['answers' => array()]);
// Act
$this->action('GET', 'ParticipantController@create');
$this->assertSessionHas('answers');
// this function is giving true
// Assert
$this->assertResponseStatus(200);
$this->flushSession();
}
}

我的没有会话的测试用例运行良好,但当我想通过嘲笑会话变量"answers"来检查它时,它仍然会给我错误。有人能帮我弄清楚我做错了什么,或者我该怎么做?如果没有这一点,我就无法继续检查代码。提前谢谢。

除了answer类型错误之外,答案数组至少需要一个元素才能通过控制器中的虚假检查。测试用例不会断言200。

在测试用例中添加一个值:

$this->session(['answers' => array('something')]);

或者更换控制器:

if (!Session::has('answers')) {

您有$this->session(['answers' => array()]);但你正在寻找答案,而不是这里的答案$this->assertSessionHas('answer');答案中的多余或缺失就是问题所在。

最新更新