Skip to content

Commit

Permalink
Merge pull request #15 from Star-Academy/test/identity-controller-test
Browse files Browse the repository at this point in the history
Test/identity controller test
  • Loading branch information
mobinbr authored Aug 20, 2024
2 parents f83656b + 008ebda commit 50bf749
Show file tree
Hide file tree
Showing 6 changed files with 300 additions and 4 deletions.
6 changes: 6 additions & 0 deletions Summer1403-Project-Group01-Backend.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Application", "src\Applicat
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Web", "src\Web\Web.csproj", "{961DAD51-ECA7-4389-8CD8-04DC47720E37}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{70322937-10C5-4B80-8096-72283A963650}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -36,5 +38,9 @@ Global
{961DAD51-ECA7-4389-8CD8-04DC47720E37}.Debug|Any CPU.Build.0 = Debug|Any CPU
{961DAD51-ECA7-4389-8CD8-04DC47720E37}.Release|Any CPU.ActiveCfg = Release|Any CPU
{961DAD51-ECA7-4389-8CD8-04DC47720E37}.Release|Any CPU.Build.0 = Release|Any CPU
{70322937-10C5-4B80-8096-72283A963650}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{70322937-10C5-4B80-8096-72283A963650}.Debug|Any CPU.Build.0 = Debug|Any CPU
{70322937-10C5-4B80-8096-72283A963650}.Release|Any CPU.ActiveCfg = Release|Any CPU
{70322937-10C5-4B80-8096-72283A963650}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
9 changes: 5 additions & 4 deletions src/Web/Helper/Errors.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
using Microsoft.AspNetCore.Mvc;
using Web.Models;

namespace Web.Helper;

public static class Errors
{
public static Object New(string title, string message)
public static ErrorResponse New(string title, string message)
{
return new
return new ErrorResponse
{
title = title,
message = new List<string> { message }
Title = title,
Message = new List<string> { message }
};
}
}
7 changes: 7 additions & 0 deletions src/Web/Models/ErrorResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Web.Models;

public class ErrorResponse
{
public string? Title { get; set; }
public List<string>? Message { get; set; }
}
9 changes: 9 additions & 0 deletions test/UnitTest1.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace test;

public class UnitTest1
{
[Fact]
public void Test1()
{
}
}
244 changes: 244 additions & 0 deletions test/Web.UnitTests/Controllers/IdentityControllerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
using System.Security.Claims;
using Application.DTOs;
using Application.DTOs.Identity;
using Application.DTOs.Identity.ChangeRole;
using Application.Interfaces.Services;
using Domain.Constants;
using Domain.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using Web.Controllers;
using Web.DTOs.Identity;
using Web.Mappers;
using Web.Models;
using Xunit.Abstractions;

namespace test.Web.UnitTests.Controllers;

public class IdentityControllerTests
{
private readonly IIdentityService _identityServiceMock;
private readonly IdentityController _controller;

public IdentityControllerTests()
{
_identityServiceMock = Substitute.For<IIdentityService>();
_controller = new IdentityController(_identityServiceMock);
}

// Signup Tests

// [Fact]
public async Task Signup_WhenUserIsNotAdmin_ReturnsForbidden()
{
// Arrange
var signupDto = new SignupDto
{
FirstName = "Mobin",
LastName = "Barfi",
Email = "[email protected]",
UserName = "MobinBarfi",
Password = "Abc@1234",
Role = "DataAnalyst"
};

_identityServiceMock.SignUpUser(Arg.Any<CreateUserRequest>()).Returns(Result<CreateUserResponse>.Ok(new CreateUserResponse()));

_controller.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
new(ClaimTypes.Role, "DataAnalyst")
}))
}
};

// Act
var result = await _controller.Signup(signupDto);

// Assert
Assert.IsType<ForbidResult>(result);
}

[Fact]
public async Task Signup_WhenRoleDoesNotExist_ReturnsBadRequest()
{
// Arrange
var signupDto = new SignupDto
{
FirstName = "Mobin",
LastName = "Barfi",
Email = "[email protected]",
UserName = "MobinBarfi",
Password = "Abc@1234",
Role = "NonExistentRole"
};

_identityServiceMock
.SignUpUser(Arg.Any<CreateUserRequest>())
.Returns(Result<CreateUserResponse>.Fail("role does not exist"));

_controller.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
new(ClaimTypes.Role, "NonExistentRole")
}))
}
};

// Act
var result = await _controller.Signup(signupDto);

// Assert
var badRequestResult = Assert.IsType<BadRequestObjectResult>(result);
Assert.Equal(400, badRequestResult.StatusCode);

var errorResponse = Assert.IsType<ErrorResponse>(badRequestResult.Value);

Assert.Equal("Signup", errorResponse.Title);
Assert.NotNull(errorResponse.Message);
Assert.Contains("role does not exist", errorResponse.Message);
}

[Fact]
public async Task Signup_WhenSignUpSucceeds_ReturnsOkResult()
{
// Arrange
var signupDto = new SignupDto
{
FirstName = "Mobin",
LastName = "Barfi",
Email = "[email protected]",
UserName = "MobinBarfi",
Password = "Abc@1234",
Role = "Admin"
};

var createUserResponse = new CreateUserResponse
{
FirstName = "Mobin",
LastName = "Barfi",
Email = "[email protected]",
UserName = "MobinBarfi",
Role = "Admin"
};

_identityServiceMock
.SignUpUser(Arg.Any<CreateUserRequest>())
.Returns(Result<CreateUserResponse>.Ok(createUserResponse));

_controller.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
new(ClaimTypes.Role, AppRoles.Admin)
}))
}
};

// Act
var result = await _controller.Signup(signupDto);

// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(200, okResult.StatusCode);

var responseValue = Assert.IsType<UserSignedUpDto>(okResult.Value);
Assert.Equal("Mobin", responseValue.FirstName);
Assert.Equal("Barfi", responseValue.LastName);
Assert.Equal("[email protected]", responseValue.Email);
Assert.Equal("MobinBarfi", responseValue.UserName);
Assert.Equal("Admin", responseValue.Role);
}

// Login Tests
[Fact]
public async Task Login_WhenLoginSucceeds_ReturnsOkResult()
{
// Arrange
var loginDto = new LoginDto
{
UserName = "MobinBarfi",
Password = "Abc@1234"
};

var mockResponse = new LoginUserResponse
{
UserName = "MobinBarfi",
Token = "FakeToken"
};

_identityServiceMock
.Login(Arg.Any<LoginUserRequest>())
.Returns(Result<LoginUserResponse>.Ok(mockResponse));

// Act
var result = await _controller.Login(loginDto);

// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var response = Assert.IsType<UserLoggedInDto>(okResult.Value);
Assert.Equal("MobinBarfi", response.UserName);
Assert.Equal("FakeToken", response.Token);
}

// ChangeRole Tests
[Fact]
public async Task ChangeRole_WhenRoleDoesNotExist_ReturnsBadRequest()
{
// Arrange
var changeRoleDto = new ChangeRoleDto
{
UserName = "MobinBarfi",
Role = "NonExistentRole"
};

_identityServiceMock
.ChangeRole(Arg.Any<ChangeRoleRequest>())
.Returns(Result.Fail("role does not exist"));

// Act
var result = await _controller.ChangeRole(changeRoleDto);

// Assert
var badRequestResult = Assert.IsType<BadRequestObjectResult>(result);
var errorResponse = Assert.IsType<ErrorResponse>(badRequestResult.Value);

Assert.Equal(400, badRequestResult.StatusCode);
Assert.Equal("ChangeRole", errorResponse.Title);
Assert.NotNull(errorResponse.Message);
Assert.Contains("role does not exist", errorResponse.Message);
}

[Fact]
public async Task ChangeRole_WhenOperationSucceeds_ReturnsOk()
{
// Arrange
var changeRoleDto = new ChangeRoleDto
{
UserName = "MobinBarfi",
Role = "Admin"
};

_identityServiceMock
.ChangeRole(Arg.Any<ChangeRoleRequest>())
.Returns(Result.Ok());

// Act
var result = await _controller.ChangeRole(changeRoleDto);

// Assert
var okResult = Assert.IsType<OkObjectResult>(result);

Assert.Equal(200, okResult.StatusCode);
Assert.Equal("Role changed successfully!", okResult.Value);
}
}
29 changes: 29 additions & 0 deletions test/test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/>
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="xunit" Version="2.5.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"/>
</ItemGroup>

<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\src\Application\Application.csproj" />
<ProjectReference Include="..\src\Web\Web.csproj" />
</ItemGroup>

</Project>

0 comments on commit 50bf749

Please sign in to comment.