如何测试此功能?
public function destroy(Post $post)
{
$post->delete();
return Response::json([], ResponseHttp::HTTP_OK);
}
我知道我必须创建几个帖子删除它,但它是如何测试的?
答案 0 :(得分:0)
你可以这样写:
public function testDestroy()
{
$post = factory(\App\Post::class)->create();
$this->call('DELETE', "post/delete/{$post->id}");
$this->assertResponseOk();
$this->assertNull(\App\Post::find($post->id));
}
答案 1 :(得分:0)
假设如下:
Example\Controller\PostController
Example\Entity\Post
然后可以测试PostController::destroy()
方法:
use Example\Entity\Post;
use Example\Controller\PostController;
use Illuminate\Http;
use PHPUnit\Framework\TestCase;
class ControllerTest extends TestCase
{
public function testDestroyDeletesPost()
{
$post = $this->createMock(Post::class);
$post
->expects($this->once())
->method('delete');
$controller = new PostController();
/** @var Http\JsonResponse $response */
$response = $controller->delete($post);
$this->assertInstanceOf(Http\JsonResponse::class, $response);
$this->assertSame(Http\Response::HTTP_OK, $response->getStatusCode());
$this->assertEquals([], $response->getData(true));
}
}
Post
的实例创建一个测试双,我们稍后会将其传递到PostController::destroy()
delete()
只被调用一次(不要担心参数,也不要返回值)PostController
PostController::delete()
,向其传递Post
的测试双精度,并在$response
变量中捕获返回值$response
Illuminate\Http\JsonResponse
Illuminate\Http\Response::HTTP_OK
供参考,见: