使用单元测试框架phpspec2运行PUT
,POST
和DELETE
的测试时遇到问题。
这是我在单元测试中的代码:
$this->beConstructedWith(new \Tonic\Application(), new \Tonic\Request(array(
'uri' => '/',
'method' => 'PUT',
'Content-Type' => 'application/json',
'data' => '{"name":"testing", "email":"testing@@test.com", "password":"Passw0rd"}'
)), array());
$expectedResult = new \stdClass();
$expectedResult->message = "An error was encountered.";
$expectedResult->error[] = "The email must be valid.";
$response = $this->exec();
$response->shouldReturnAnInstanceOf("Tonic\Response");
$response->contentType->shouldBe("application/json");
$response->body->shouldBe(json_encode($expectedResult));
通过查看Tonic代码和git repository中的示例,我认为我已将其设置正确。
以下是为此单元测试运行bin/phpspec -v run
的结果:
当我针对Tonic服务运行实际请求时,它工作正常。我知道我必须在单元测试的设置中做错了但我不知道是什么。
修改:PUT方法
/**
* Add a new user to the table.
*
* @method PUT
* @accepts application/json
* @provides application/json
* @json
* @return \Tonic\Response
*/
public function add()
{
// Validate the data before we go any futher.
$error = $this->validate();
// If the data is invalid then we want to let the requester know.
if (true === $error) {
$this->output->message = "An error was encountered.";
$this->responseCode = \Tonic\Response::NOTFOUND;
} else { // Else we want to PUT the data into our table.
$query = $this->db->prepare("INSERT INTO `user` (`name`, `email`, `password`, `dateOfBirth`) VALUES (:name, :email, :password, :dateOfBirth)");
$query->bindValue(":name", $this->request->data->name);
$query->bindValue(":email", $this->request->data->email);
$query->bindValue(":password", hash('sha256', $this->request->data->password));
$query->bindValue(":dateOfBirth", $this->request->data->dateOfBirth);
$query->execute();
// Check that the new user was successfully inserted into the database. If not let the requester know what happened.
if (0 === $query->rowCount()) {
if ("00000" === $query->errorCode()) {
$this->output->message = "No rows affected by query.";
} else {
$this->output->message = "There was an error running the query.";
$this->output->error[] = $query->errorInfo();
}
$this->responseCode = \Tonic\Response::CONFLICT;
} else { // Inserted successfully.
$this->output->message = "User successfully created.";
$this->responseCode = \Tonic\Response::CREATED;
$this->headers["Location"] = "/" . $this->request->data->email;
}
}
return new \Tonic\Response($this->responseCode, $this->output, $this->headers);
}
答案 0 :(得分:1)
好的,所以我明白了。问题与以下代码中的Content-Type
设置有关:
$this->beConstructedWith(new \Tonic\Application(), new \Tonic\Request(array(
'uri' => '/',
'method' => 'PUT',
'Content-Type' => 'application/json',
'data' => '{"name":"testing", "email":"testing@@test.com", "password":"Passw0rd"}'
)), array());
应为contentType
:
$this->beConstructedWith(new \Tonic\Application(), new \Tonic\Request(array(
'uri' => '/',
'method' => 'PUT',
'contentType' => 'application/json',
'data' => '{"name":"testing", "email":"testing@@test.com", "password":"Passw0rd"}'
)), array());