我正在从事SilverStripe项目。我正在为我的单元测试编写功能测试。以下是我要测试的方案。发出POST请求时,我将请求主体中的数据保存到SilverStripe会话中。我想断言/测试数据是否存储在会话中。
这是我的控制器类
class CustomFormPageController extends PageController
{
private static $allowed_actions = [
'testPostRequest',
];
private static $url_handlers = [
'testPostRequest' => 'testPostRequest',
];
public function testPostRequest(HTTPRequest $request)
{
if (! $request->isPOST()) {
return "Bad request";
}
//here I am saving the data in the session
$session = $request->getSession();
$session->set('my_session_key', $request->getBody());
return "Request successfully processed";
}
}
下面是我的测试课
class CustomFormPageTest extends FunctionalTest
{
protected static $fixture_file = 'fixtures.yml';
public function testTestingPost()
{
$formPage = $this->objFromFixture(CustomFormPage::class, 'form_page');
$response = $this->post($formPage->URLSegment . '/testPostRequest', [
'name' => 'testing'
]);
$request = Injector::inst()->get(HTTPRequest::class);
$session = $request->getSession();
$sessionValue = $session->get('my_session_key');
var_dump($sessionValue);
}
}
[运行测试时,出现以下错误。
ArgumentCountError: Too few arguments to function SilverStripe\Control\HTTPRequest::__construct(), 0 passed and at least 2 expected
我该如何解决?如何测试数据是否存储在会话中?
我也尝试过,它总是返回NULL
var_dump($this->session()->get('my_session_key');
您收到的错误是在创建当前请求之前向Injector询问当前请求时发生的。这是因为FunctionalTest嵌套了执行测试的状态。
如上所述,您仍然可以使用$this->session()
访问FunctionalTest会话。
测试失败的主要原因是未发布固定页面,并且默认情况下FunctionalTest在实时阶段运行(我假设是这样,因为您没有发布固定设备)。您可以在测试课程中使用protected static $use_draft_site = true;
使用草稿阶段,也可以在向其发出POST请求之前在setUp()
或测试中发布页面。
您的下一个问题是$request->getBody()
在您的控制器中为空,因此未设置任何内容。
此示例,例如:
//here I am saving the data in the session
$session = $request->getSession();
$session->set('my_session_key', $request->postVar('name'));
$response = $this->post($formPage->URLSegment . '/testPostRequest', [
'name' => 'testing'
], [], $this->session());
$sessionValue = $this->session()->get('my_session_key');
$this->assertSame('testing', $sessionValue);