Hi everyone,
I'm currently trying to write unit tests for my AuthController in Laravel. However, I'm unsure whether my approach qualifies as a unit test or if it's more of a feature test
Here is my AuthController I´m working with:
public function login(Request $request)
{
$validator = Validator::make($request->only('username', 'password'), [
'username' => 'required|string|max:255',
'password' => 'required|string|min:8',
]);
if ($validator->fails()) {
return response()->json(['message' => 'Validation failed'], 422);
}
if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {
$user = Auth::user();
$token = $user->createToken('UserAuth')->plainTextToken;
return response()->json(['user' => $user, 'token' => $token], 200);
}
return response()->json(['message' => 'Invalid credentials'], 401);
}
There are a few unit tests i wrote
lass AuthControllerTest extends TestCase
{
/**
* A basic unit test example.
*/
use RefreshDatabase;
#[\PHPUnit\Framework\Attributes\Test]
public function Test_true_credentials_login_(): void
{
$role = Role::create(['role_name' => 'Patient']);
$user = User::create([
'username' => 'Pxscal',
'password' => 'Blubberbernd123',
'role_id' => $role->role_id,
]);
$response = $this->call('POST','/api/login',[
'username' => 'Pxscal',
'password'=> 'Blubberbernd123',
]);
$response->assertStatus(200);
}
#[\PHPUnit\Framework\Attributes\Test]
public function Test_false_password_login_(): void
{
$role = Role::create(['role_name' => 'Patient']);
$user = User::create([
'username' => 'Pxscal',
'password' => 'Blubberbernd1234',
'role_id' => $role->role_id,
]);
$response = $this->call('POST','/api/login',[
'username' => 'Pxscal',
'password'=> 'Blubberbernd123',
]);
$response->assertStatus(401);
}
Thanks for help!