public async Task RequestFriendshipCommandHandler_ShouldReturnCreatedFriendship() { // Arrange RequestFriendshipCommand request = new RequestFriendshipCommand { AddresseeId = 2 }; _unitOfWorkMock .Setup(m => m.CommitAsync(It.IsAny <CancellationToken>())) .ReturnsAsync(1); _unitOfWorkMock .Setup(m => m.Friendships.Add(It.IsAny <Friendship>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask) .Callback <Friendship, CancellationToken>((f, _) => f.FriendshipId = 1); RequestFriendshipCommand.Handler handler = new RequestFriendshipCommand.Handler(_userProviderMock.Object, _unitOfWorkMock.Object, _dateProviderMock.Object, _mapperMock); // Act FriendshipResource friendship = await handler.Handle(request); // Assert Assert.NotNull(friendship); Assert.NotEqual(0, friendship.FriendshipId); Assert.Equal(1, friendship.RequesterId); Assert.Equal(2, friendship.AddresseeId); }
public async Task <ActionResult <FriendshipResource> > RequestFriendship([FromBody] RequestFriendshipBody body, CancellationToken cancellationToken = default) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Get the current user id int requesterId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); // Check if requester + addressee id are the same if (requesterId == body.AddresseeId) { return(StatusCode(StatusCodes.Status403Forbidden, new ErrorResource { StatusCode = StatusCodes.Status403Forbidden, Message = "You cannot create a friendship with yourself" })); } // Check if the addressed user exists UserExistsQuery existsQuery = new UserExistsQuery { UserId = body.AddresseeId }; bool userExists = await _mediator.Send(existsQuery, cancellationToken); if (!userExists) { return(NotFound(new ErrorResource { StatusCode = StatusCodes.Status404NotFound, Message = $"User with ID '{body.AddresseeId}' does not exist" })); } // Check if there is already a friendship with the given user combination FriendshipCombinationExistsQuery combinationExistsQuery = new FriendshipCombinationExistsQuery { RequesterId = requesterId, AddresseeId = body.AddresseeId }; bool combinationExists = await _mediator.Send(combinationExistsQuery, cancellationToken); if (combinationExists) { return(StatusCode(StatusCodes.Status403Forbidden, new ErrorResource { StatusCode = StatusCodes.Status403Forbidden, Message = $"There is already a friendship with user {body.AddresseeId}" })); } // Create friendship RequestFriendshipCommand command = _mapper.Map <RequestFriendshipBody, RequestFriendshipCommand>(body); FriendshipResource friendship = await _mediator.Send(command, cancellationToken); return(CreatedAtAction(nameof(GetFriendshipById), new { friendshipId = friendship.FriendshipId }, friendship)); }