public async Task CreateMembership_ShouldReturnNotFoundResult_WhenUserDoesNotExist() { // Arrange CreateMembershipBody body = new CreateMembershipBody { GroupId = 1, UserId = 751, IsAdmin = false }; Mock <IMediator> mediatorMock = new Mock <IMediator>(); mediatorMock .Setup(m => m.Send(It.IsAny <GroupExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); mediatorMock .Setup(m => m.Send(It.IsAny <UserExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); GroupMembershipController controller = new GroupMembershipController(mediatorMock.Object, null); // Act ActionResult <GroupMembershipResource> response = await controller.CreateMembership(body); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response.Result); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.NotNull(error); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public async Task GetFundingStructure_GivenNoSpecificationFoundForPublishedProviderVersion_ReturnsNotFound() { string publishedProviderVersionId = NewRandomString(); string specificationId = NewRandomString(); string fundingPeriodId = NewRandomString(); string providerId = NewRandomString(); string fundingStreamId = NewRandomString(); int templateVersion = NewRandomNumber(); PublishedProviderVersion publishedProviderVersion = NewPublishedProviderVersion(_ => _ .WithFundingStreamId(fundingStreamId) .WithFundingPeriodId(fundingPeriodId) .WithProviderId(providerId) .WithSpecificationId(specificationId)); _publishedFundingRepository.GetPublishedProviderVersionById(publishedProviderVersionId) .Returns(publishedProviderVersion); _specificationService.GetSpecificationSummaryById(specificationId) .Returns((SpecificationSummary)null); var result = await _service.GetPublishedProviderFundingStructure(publishedProviderVersionId); NotFoundObjectResult notFoundObjectResult = result.Should() .BeAssignableTo <NotFoundObjectResult>() .Which .As <NotFoundObjectResult>(); notFoundObjectResult.Value .Should() .Be($"Specification not found for SpecificationId - {specificationId}"); }
public IActionResult NotFoundObjectResult() { //This is a test var result = new NotFoundObjectResult(new { message = "404 Not Found", currentDate = DateTime.Now }); return(result); }
public static NotFoundObjectResult NotFound(string message = "Not found.") { var res = new Response(HttpStatusCode.NotFound, message, null); var obj = new NotFoundObjectResult(res); return(obj); }
public void OnException(ExceptionContext context) { if (context.Exception is AcmeException acmeException) { _logger.LogDebug($"Detected {acmeException.GetType()}. Converting to BadRequest."); #if DEBUG _logger.LogError(context.Exception, "AcmeException detected."); #endif ObjectResult result; if (acmeException is ConflictRequestException) { result = new ConflictObjectResult(acmeException.GetHttpError()); } else if (acmeException is NotAllowedException) { result = new UnauthorizedObjectResult(acmeException.GetHttpError()); } else if (acmeException is NotFoundException) { result = new NotFoundObjectResult(acmeException.GetHttpError()); } else { result = new BadRequestObjectResult(acmeException.GetHttpError()); } result.ContentTypes.Add("application/problem+json"); context.Result = result; } }
public void TestPutNotFoundObject() { TouristSpot touristSpotToUpdate = new TouristSpot() { Name = "Virgen del verdún", Id = 3 }; TouristSpot newData = new TouristSpot() { Name = "The Green Roofs", }; TouristSpotModelIn touristSpotModelToUpdate = new TouristSpotModelIn(touristSpotToUpdate); TouristSpotModelIn newDataModel = new TouristSpotModelIn(newData); var mock = new Mock <ITouristSpotLogic>(MockBehavior.Strict); mock.Setup(ts => ts.Update(touristSpotModelToUpdate.Id, newData)); mock.Setup(ts => ts.Get(touristSpotToUpdate.Id)).Throws(new ObjectNotFoundInDatabaseException()); var controller = new TouristSpotController(mock.Object); var result = controller.Put(touristSpotModelToUpdate.Id, newDataModel) as NotFoundObjectResult; var expectedResult = new NotFoundObjectResult("There is no tourist spot with such id."); mock.VerifyAll(); Assert.AreEqual(expectedResult.Value, result.Value); }
public async Task UpdateGroup_ShouldReturnNotFoundResult_WhenGroupDoesNotExist() { // Arrange const int groupId = 15453; UpdateGroupBody model = new UpdateGroupBody { Name = "Some updated name", Description = "Some updated description" }; Mock <IMediator> mediatorMock = new Mock <IMediator>(); mediatorMock .Setup(m => m.Send(It.IsAny <GroupExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); GroupController controller = new GroupController(mediatorMock.Object, null); // Act ActionResult response = await controller.UpdateGroup(groupId, model); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public async Task GetProviderDataForReleaseAsCsv_ShouldReturnNotFoundResultWhenNoDataFoundForGivenPublishedProviderIds() { IEnumerable <string> publishedProviderIds = new[] { NewRandomString(), NewRandomString() }; string specificationId = NewRandomString(); _validator.Validate(Arg.Is(specificationId)) .Returns(new ValidationResult()); PublishedProviderStatus[] statuses = new[] { PublishedProviderStatus.Approved }; GivenTheFundingDataForCsv(Enumerable.Empty <PublishedProviderFundingCsvData>(), publishedProviderIds, specificationId, statuses); NotFoundObjectResult result = await WhenTheGetProviderDataForBatchReleaseAsCsvExecuted(publishedProviderIds, specificationId) as NotFoundObjectResult; result .Should() .NotBeNull(); result.Value .Should() .BeOfType <string>() .Which .Should() .Be("No data found for given specification and published provider ids."); }
public async Task GetTranslationsByLangauge_ShouldReturnNotFoundResult_WhenLanguageDoesNotExist() { // Arrange const int languageId = 8941; GetTranslationsByLanguageQueryParams model = new GetTranslationsByLanguageQueryParams(); Mock <IMediator> mediatorMock = new Mock <IMediator>(); mediatorMock .Setup(m => m.Send(It.IsAny <LanguageExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); LanguageController controller = new LanguageController(mediatorMock.Object); // Act ActionResult <IDictionary <string, string> > response = await controller.GetTranslationsByLanguage(languageId, model); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response.Result); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public override void OnException(ExceptionContext context) { Exception ex = context.Exception; string correlationId = context.HttpContext.GetCorrelationId(); IActionResult result; ExceptionContract errorData; if (ex is BusinessLogicException businessLogicException) { errorData = new ExceptionContract(businessLogicException, correlationId); if (ex is EntityNotFoundException) { result = new NotFoundObjectResult(errorData); } else { result = new BadRequestObjectResult(errorData); } } else { errorData = new ExceptionContract(DEFAULT_ERROR_MESSAGE, DEFAULT_ERROR_CODE, correlationId); result = new ObjectResult(errorData) { StatusCode = StatusCodes.Status500InternalServerError }; } context.Result = result; }
/// <summary> /// Forges an API error response based on a given dictionary and returns it. /// Make sure you check if the dictionary contains an error first. /// </summary> private IActionResult ForgeErrorResponse(Dictionary <ServiceDictionaryKey, object> dictionary) { IActionResult actionResult = new BadRequestObjectResult(dictionary[ServiceDictionaryKey.ERROR]); // HttpStatusCode provided, so we handle that too if (dictionary.ContainsKey(ServiceDictionaryKey.HTTPSTATUSCODE)) { switch (dictionary[ServiceDictionaryKey.HTTPSTATUSCODE]) { case HttpStatusCode.NotFound: actionResult = new NotFoundObjectResult(dictionary[ServiceDictionaryKey.ERROR]); break; case HttpStatusCode.Forbidden: actionResult = new BadRequestObjectResult("(403) Forbidden: " + dictionary[ServiceDictionaryKey.ERROR]); break; default: actionResult = new BadRequestObjectResult(dictionary[ServiceDictionaryKey.ERROR]); break; } } return(actionResult); }
private IActionResult CreateErrorResult(Result result) { ActionResult actionResult; ModelStateDictionary modelState = GetErrors(result); ValidationResult res = result.Notifications.FirstOrDefault(x => !x.IsValid); if (res == null || res.Errors.Count == 0) { return(new BadRequestObjectResult(modelState)); } switch (res.Errors.First().ErrorCode) { case nameof(ErrorType.NotFound): actionResult = new NotFoundObjectResult(modelState); break; case nameof(ErrorType.BadRequest): actionResult = new UnprocessableEntityObjectResult(modelState); break; case nameof(ErrorType.Unauthorized): actionResult = new UnauthorizedResult(); break; default: actionResult = new BadRequestObjectResult(modelState); break; } return(actionResult); }
public async Task <ObjectResult> UpdateCurrentAsync(CancellationToken cancellationToken = default) { var userFromIdentity = GetUserFromIdentity(); try { var user = await _userService.UpdateAsync(userFromIdentity, cancellationToken); var userViewModel = _mapper.Map <UserInfoViewModel>(user); var result = new OkObjectResult(userViewModel); return(result); } catch (UserEmailNotVerifiedException) { var modelState = new ModelStateDictionary(); modelState.AddModelError(nameof(UserInfo.IsEmailVerified), "Email is not verified"); var badResult = new BadRequestObjectResult(modelState); return(badResult); } catch (UserNotFoundException) { var badResult = new NotFoundObjectResult(null); return(badResult); } }
public async Task ListDatasetSchemasModel_OnGet_WhenSpecificationNotFoundThenStatusCodeNotFoundReturned() { // Arrange IDatasetsApiClient datasetClient = Substitute.For <IDatasetsApiClient>(); ISpecsApiClient specsClient = Substitute.For <ISpecsApiClient>(); IMapper mapper = MappingHelper.CreateFrontEndMapper(); ILogger logger = Substitute.For <ILogger>(); string expectedSpecificationId = "1"; Specification expectedSpecification = null; specsClient .GetSpecification(Arg.Any <string>()) .Returns(new ApiResponse <Specification>(HttpStatusCode.NotFound, expectedSpecification)); ListDatasetSchemasModel listDatasetSchemasPageModel = new ListDatasetSchemasModel(specsClient, datasetClient, mapper); // Act IActionResult result = await listDatasetSchemasPageModel.OnGet(expectedSpecificationId); // Assert result.Should().NotBeNull(); result.Should().BeOfType <NotFoundObjectResult>(); NotFoundObjectResult typeResult = result as NotFoundObjectResult; typeResult.Value.Should().Be("Specification not found"); }
public void PostTestWrongExtensionReturnsErrorMessage() { //Arrange var txtFileName = "Data.txt"; TestFileHelper tstHelper = new TestFileHelper(txtFileName, ""); FilesController fileController = new FilesController(tstHelper.config.Object, new CsvFileHandler(new ValidationService(), new FileService(tstHelper.config.Object), new ParsingService())); // Expected result var expectedResult = new NotFoundObjectResult(new { message = $"Selected file, {txtFileName}, does not have supported format CSV" }); //Act var actualResult = fileController.Post(new List <IFormFile>() { tstHelper.fileMock.Object }, true); //Assert Assert.IsNotNull(actualResult); Assert.IsNotNull(actualResult.Result); Assert.AreEqual(expectedResult.StatusCode, ((NotFoundObjectResult)actualResult.Result).StatusCode); Assert.AreEqual(expectedResult.Value.ToString(), ((NotFoundObjectResult)actualResult.Result).Value.ToString()); }
public void GetAccountBalanceNotFound() { IActionResult account = controller.Get("500"); NotFoundObjectResult actionresult = account as NotFoundObjectResult; Assert.Equal(404, actionresult.StatusCode); }
public static NotFoundObjectResult NotFoundObjectResult(ResponseType responseType) { NotFoundObjectResult notFoundResult = new NotFoundObjectResult(Constants.ResponseDictionary[responseType]); notFoundResult.StatusCode = StatusCodes.Status404NotFound; return(notFoundResult); }
public ActionResult <Environment> Delete(int id) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Environment env = _envService.FindById(id); if (env != null) { _context.Environments.Remove(env); var retorno = _envService.SaveOrUpdate(env); return(Ok(retorno)); } else { object res = null; NotFoundObjectResult notfound = new NotFoundObjectResult(res); notfound.StatusCode = 404; notfound.Value = "O Environment " + id + " não foi encontrado!"; return(NotFound(notfound)); } }
public void GetCustomerByIdNotFound() { IActionResult customers = controller.Get(100); NotFoundObjectResult actionresult = customers as NotFoundObjectResult; Assert.Equal(404, actionresult.StatusCode); }
protected async Task <ObjectResult> CreateInfoObjectResult <T>(Func <string, Task <ResultViewModel> > fillResultModelFunc, string email) { ObjectResult result; ResultViewModel resultViewModel = await fillResultModelFunc.Invoke(email); switch (resultViewModel.Flag) { case (int)HttpStatusCode.NotFound: result = new NotFoundObjectResult(resultViewModel.Information); break; case (int)HttpStatusCode.BadRequest: result = new BadRequestObjectResult(resultViewModel.Information); break; case (int)HttpStatusCode.OK: result = new OkObjectResult(resultViewModel.Information); break; default: result = new BadRequestObjectResult(UNKNOWN_ERROR_MESSAGE); break; } return(result); }
public void CreateCommentByNoExistingUser() { //Arrange. ControllerContext fakeContext = GetFakeControllerContext(); controller.ControllerContext = fakeContext; CommentModelIn input = new CommentModelIn() { Text = "this is a comment" }; Exception internalEx = new UserNotFoundException(); Exception toThrow = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND); matchService.Setup(ms => ms.CommentOnEncounter(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>())).Throws(toThrow); //Act. IActionResult result = controller.CommentOnMatch(3, input); NotFoundObjectResult badRequest = result as NotFoundObjectResult; ErrorModelOut error = badRequest.Value as ErrorModelOut; //Assert. matchService.Verify(ms => ms.CommentOnEncounter(3, "username", input.Text), Times.Once); Assert.IsNotNull(result); Assert.IsNotNull(badRequest); Assert.AreEqual(404, badRequest.StatusCode); Assert.IsNotNull(error); Assert.AreEqual(error.ErrorMessage, toThrow.Message); }
public async Task EditMessage_ShouldReturnNotFoundResult_WhenMessageDoesNotExist() { // Arrange const int messageId = 1; EditMessageBody body = new EditMessageBody { HtmlContent = "<p>hello world</p>" }; _mediatorMock .Setup(m => m.Send(It.IsAny <MessageExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); MessageController controller = new MessageController(null, _mediatorMock.Object); // Act ActionResult response = await controller.EditMessage(messageId, body); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.NotNull(error); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public async Task PasswordResetEmail_PasswordResetLinkNotSent_ReturnsNotFound() { string email = "fake_email"; string resetCode = Guid.NewGuid().ToString(); var registration = new Mock <IRegistration>(); var httpContext = new DefaultHttpContext(); var uriBuilder = new UriBuilder { Scheme = httpContext.Request.Scheme, Host = httpContext.Request.Host.ToString(), Path = $"/user/ResetPassword/{resetCode}" }; var link = uriBuilder.ToString(); registration.Setup(register => register.SendPasswordResetLinkEmail(email, link)).ReturnsAsync("User not found..."); var controllerContext = new ControllerContext() { HttpContext = httpContext, }; var forgotPasswordController = new ForgotPasswordController(registration.Object) { ControllerContext = controllerContext, }; var result = await forgotPasswordController.PasswordResetEmail(email); var notFoundResult = new NotFoundObjectResult(result); Assert.AreEqual(404, notFoundResult.StatusCode); }
public async Task SendMessage_ShouldReturnNotFoundResult_WhenRecipientDoesNotExist() { // Arrange SendMessageBody body = new SendMessageBody { RecipientId = 4314, HtmlContent = "hello world" }; _mediatorMock .Setup(m => m.Send(It.IsAny <RecipientExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); MessageController controller = new MessageController(null, _mediatorMock.Object); // Act ActionResult <ChatMessageResource> response = await controller.SendMessage(body); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response.Result); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.NotNull(error); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public async Task UpdateFriendshipStatus_ShouldReturnNotFound_WhenFriendshipDoesNotExist() { // Arrange const int friendshipId = 87921; UpdateFriendshipStatusBody model = new UpdateFriendshipStatusBody { FriendshipStatusId = FriendshipStatusId.Accepted }; Mock <IMediator> mediatorMock = new Mock <IMediator>(); mediatorMock .Setup(m => m.Send(It.IsAny <FriendshipExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); FriendshipController controller = new FriendshipController(mediatorMock.Object, null); // Act ActionResult response = await controller.UpdateFriendshipStatus(friendshipId, model); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public async Task UpdateMembership_ShouldReturnNotFoundResult_WhenMembershipDoesNotExist() { // Arrange const int membershipId = 56431; UpdateMembershipBody body = new UpdateMembershipBody { IsAdmin = true }; Mock <IMediator> mediatorMock = new Mock <IMediator>(); mediatorMock .Setup(m => m.Send(It.IsAny <MembershipExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); GroupMembershipController controller = new GroupMembershipController(mediatorMock.Object, null); // Act ActionResult response = await controller.UpdateMembership(membershipId, body); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.NotNull(error); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public async Task LinkActorWithMovie_NonExistingMovie_ReturnsNotFound(int actorId, int movieId) { //Arrange var actorList = new List <Actor>() { new Actor() { Id = actorId } }; Mock <IQueryable <Actor> > mockActors = actorList.AsQueryable().BuildMock(); _mockActorRepository.Setup(x => x.GetAll()).Returns(mockActors.Object); Mock <IQueryable <Movie> > mockMovies = new List <Movie>().AsQueryable().BuildMock(); _mockMovieRepository.Setup(x => x.GetAll()).Returns(mockMovies.Object); //ACT IActionResult result = await _controller.LinkActorWithMovie(actorId, movieId); //ASSERT NotFoundObjectResult notFoundObjectResult = Assert.IsType <NotFoundObjectResult>(result); Assert.Equal(nameof(movieId), notFoundObjectResult.Value); }
public async Task <IActionResult> Index() { // If root role already exists in the system, return 404 if (await _roleManager.RoleExistsAsync("root")) { var notFoundObject = new NotFoundObjectResult(this.NotFound()); return(NotFound()); } // Create root and admin roles and assign them to the current user List <string> rolesList = new List <string>(); IdentityResult rootResult = await _roleManager.CreateAsync(new IdentityRole("root")); if (rootResult.Succeeded == true) { rolesList.Add("root"); IdentityResult adminResult = await _roleManager.CreateAsync(new IdentityRole("admin")); if (adminResult.Succeeded == true) { rolesList.Add("admin"); var currentUser = await _userManager.GetUserAsync(User); await _userManager.AddToRolesAsync(currentUser, rolesList); } } return(RedirectToAction("Index", "Home")); }
public static string GetNotFoundError(IActionResult actual) { Assert.IsInstanceOf <NotFoundObjectResult>(actual); NotFoundObjectResult result = actual as NotFoundObjectResult; return(result.Value?.ToString()); }
public void GetByNonExistantIdReturnsNotFound() { IActionResult result = _controller.Get(99); NotFoundObjectResult objectResult = result as NotFoundObjectResult; Assert.IsNotNull(objectResult); }
public void HttpNotFoundObjectResult_InitializesStatusCode() { // Arrange & act var notFound = new NotFoundObjectResult(null); // Assert Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode); }
public void HttpNotFoundObjectResult_InitializesStatusCodeAndResponseContent() { // Arrange & act var notFound = new NotFoundObjectResult("Test Content"); // Assert Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode); Assert.Equal("Test Content", notFound.Value); }
public async Task HttpNotFoundObjectResult_ExecuteSuccessful() { // Arrange var httpContext = GetHttpContext(); var actionContext = new ActionContext() { HttpContext = httpContext, }; var result = new NotFoundObjectResult("Test Content"); // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode); }