Skip to content

Commit bc83087

Browse files
committed
testing post controller
1 parent 5e8a18d commit bc83087

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

tests/Feature/PostTest.php.php

+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
<?php
2+
3+
namespace Tests\Feature;
4+
5+
use App\Models\Post;
6+
use App\Models\User;
7+
use Illuminate\Foundation\Testing\RefreshDatabase;
8+
use Illuminate\Foundation\Testing\WithFaker;
9+
use Illuminate\Support\Facades\Hash;
10+
use Laravel\Sanctum\Sanctum;
11+
use Tests\TestCase;
12+
13+
class PostTest extends TestCase
14+
{
15+
use RefreshDatabase, WithFaker;
16+
17+
public function testDeletePost()
18+
{
19+
20+
$user = User::factory()->create();
21+
$post = Post::factory()->create(['user_id' => $user->id]);
22+
23+
24+
$this->actingAs($user);
25+
26+
27+
$response = $this->delete('/posts/' . $post->id);
28+
29+
30+
$response->assertStatus(200);
31+
$response->assertJson([
32+
'message' => 'Post deleted successfully'
33+
]);
34+
35+
36+
$response->assertDeleted($post);
37+
}
38+
39+
public function testCreatePost()
40+
{
41+
42+
$user = User::factory()->create();
43+
$postData = [
44+
'title' => 'Test Post',
45+
'content' => 'This is a test post',
46+
'user_id' => $user->id,
47+
];
48+
49+
50+
$this->actingAs($user);
51+
52+
53+
$response = $this->post('/posts', $postData);
54+
55+
56+
$response->assertStatus(201);
57+
$response->assertJson([
58+
'message' => 'Post created successfully',
59+
'data' => [
60+
'title' => 'Test Post',
61+
'content' => 'This is a test post',
62+
'user_id' => $user->id,
63+
],
64+
]);
65+
66+
67+
$this->assertDatabaseHas('posts', [
68+
'title' => 'Test Post',
69+
'content' => 'This is a test post',
70+
'user_id' => $user->id,
71+
]);
72+
}
73+
74+
public function testGetPosts()
75+
{
76+
77+
$user = User::factory()->create();
78+
$post = Post::factory()->create(['user_id' => $user->id]);
79+
80+
81+
$response = $this->get('/api/home/posts');
82+
83+
84+
$response->assertStatus(200);
85+
86+
87+
$response->assertJsonFragment([
88+
'user_name' => $user->name,
89+
'user_imageUrl' => $user->imageUrl,
90+
91+
]);
92+
}
93+
94+
95+
public function testEditPost()
96+
{
97+
$user = User::factory()->create();
98+
$post = Post::factory()->create(['user_id' => $user->id]);
99+
100+
101+
$requestData = [
102+
'content' => 'New content',
103+
104+
];
105+
106+
107+
$response = $this->put("/api/home/posts/{$post->id}", $requestData);
108+
109+
110+
$response->assertStatus(200);
111+
112+
113+
$response->assertJsonFragment([
114+
'user_name' => $user->name,
115+
'user_imageUrl' => $user->imageUrl,
116+
'content' => 'New content',
117+
118+
]);
119+
}
120+
}

0 commit comments

Comments
 (0)