public void ToShouldThrowExceptionWithUnsupportedMediaType() { MyWebApi .Routes() .ShouldMap("api/Route/PostMethodWithModel") .WithHttpMethod(HttpMethod.Post) .WithContent( @"{""Integer"": 1, ""RequiredString"": ""Test"", ""NonRequiredString"": ""AnotherTest"", ""NotValidateInteger"": 2}", MediaType.TextPlain) .To <RouteController>(c => c.PostMethodWithModel(new RequestModel { Integer = 1, RequiredString = "Test", NonRequiredString = "AnotherTest", NotValidateInteger = 2 })); }
public void ToShouldResolveCorrectyWithJsonContent() { MyWebApi .Routes() .ShouldMap("api/Route/PostMethodWithModel") .WithHttpMethod(HttpMethod.Post) .WithJsonContent( @"{""Integer"": 1, ""RequiredString"": ""Test"", ""NonRequiredString"": ""AnotherTest"", ""NotValidateInteger"": 2}") .To <RouteController>(c => c.PostMethodWithModel(new RequestModel { Integer = 1, RequiredString = "Test", NonRequiredString = "AnotherTest", NotValidateInteger = 2 })); }
public void WithModelStateShouldThrowExceptionWhenModelStateHasMoreErrors() { var requestModelWithErrors = TestObjectFactory.GetRequestModelWithErrors(); var modelState = new ModelStateDictionary(); modelState.AddModelError("Integer", "The field Integer must be between 1 and 2147483647."); modelState.AddModelError("RequiredString", "The RequiredString field is not required."); modelState.AddModelError("RequiredString", "The RequiredString field is required."); MyWebApi .Controller <WebApiController>() .Calling(c => c.BadRequestWithModelState(requestModelWithErrors)) .ShouldReturn() .BadRequest() .WithModelState(modelState); }
public void ContainingFormattersShouldNotThrowExceptionWhenActionResultHasCorrectMediaTypeFormattersAsParams() { var mediaTypeFormatters = TestObjectFactory.GetFormatters().ToList(); MyWebApi .Controller <WebApiController>() .Calling(c => c.CreatedActionWithCustomContentNegotiator()) .ShouldReturn() .Created() .ContainingMediaTypeFormatters( mediaTypeFormatters[0], mediaTypeFormatters[1], mediaTypeFormatters[2], mediaTypeFormatters[3], mediaTypeFormatters[4]); }
public void PostShouldBeMappedCorrectly() { MyWebApi .Routes() .ShouldMap("/api/Gadgets") .WithHttpMethod(HttpMethod.Post) .WithJsonContent(@"{""Name"":""Valid Name"",""Description"":""Valid Description"",""Price"":""1"",""Image"":""Valid Image""}") .To <GadgetsController>(c => c.PostOrder(new GadgetViewModel() { Name = "Valid Name", Description = "Valid Description", Price = 1, Image = "Valid Image" } )).ToValidModelState(); }
public void AndProvideShouldReturnProperHttpRequestMessage() { var httpRequestMessage = MyWebApi .Controller <WebApiController>() .WithHttpRequestMessage(request => request .WithMethod(HttpMethod.Get) .WithHeader("TestHeader", "TestHeaderValue")) .Calling(c => c.HttpResponseMessageAction()) .ShouldReturn() .HttpResponseMessage() .AndProvideTheHttpRequestMessage(); Assert.IsNotNull(httpRequestMessage); Assert.AreEqual(HttpMethod.Get, httpRequestMessage.Method); Assert.IsTrue(httpRequestMessage.Headers.Contains("TestHeader")); }
public void GetShouldReturnOkWhenProjectIsNotNull() { MyWebApi .Controller <ProjectsController>() .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService()) .WithAuthenticatedUser() .Calling(c => c.Get("Valid")) .ShouldReturn() .Ok() .WithResponseModelOfType <SoftwareProjectDetailsResponseModel>() .Passing(pr => { Assert.AreEqual(new DateTime(2015, 11, 5, 23, 47, 12), pr.CreatedOn); Assert.AreEqual("Test", pr.Name); Assert.AreEqual(0, pr.TotalUsers); }); }
public void GetWithBothBiggerShouldReturnFiltered() { MyWebApi .Controller <CommentsController>() .WithResolvedDependencies(Services.GetCommentServices()) .Calling(c => c.Get("TestUser 1", new QueryRealEstates() { Skip = 3, Take = 3 })) .ShouldReturn() .Ok() .WithResponseModelOfType <List <CommentResponseModel> >() .Passing(model => { Assert.AreEqual(0, model.Count); }); }
public async Task DeletingImagesShouldWorkCorrectly() { var dummyImageService = DummyServices.GetDummyImagesService(); var currentImagesCount = dummyImageService.All().Count(); var result = await MyWebApi .Controller <ImagesController>() .WithResolvedDependencies(dummyImageService) .Calling(c => c.Delete(3)) .ShouldReturn() .ResultOfType <Task <IHttpActionResult> >() .AndProvideTheModel(); var newImageCount = dummyImageService.All().Count(); Assert.IsTrue(newImageCount == currentImagesCount - 1); }
public void WithoutAnyConfigurationShouldInstantiateDefaultOne() { MyWebApi.IsUsing(null); var config = MyWebApi .Controller <WebApiController>() .WithHttpRequestMessage(request => request.WithMethod(HttpMethod.Get)) .Calling(c => c.CustomRequestAction()) .ShouldReturn() .BadRequest() .AndProvideTheController() .Configuration; Assert.IsNotNull(config); MyWebApi.IsUsing(TestObjectFactory.GetHttpConfigurationWithRoutes()); }
public void WithAuthenticatedNotCalledShouldNotHaveAuthorizedUser() { var controllerBuilder = MyWebApi .Controller <WebApiController>(); controllerBuilder .Calling(c => c.AuthorizedAction()) .ShouldReturn() .NotFound(); var controllerUser = controllerBuilder.AndProvideTheController().User; Assert.AreEqual(false, controllerUser.IsInRole("Any")); Assert.AreEqual(null, controllerUser.Identity.Name); Assert.AreEqual(null, controllerUser.Identity.AuthenticationType); Assert.AreEqual(false, controllerUser.Identity.IsAuthenticated); }
public void WithAuthenticatedUserUsingPrincipalShouldWorkCorrectly() { var controllerBuilder = MyWebApi .Controller <WebApiController>(); controllerBuilder .WithAuthenticatedUser(TestObjectFactory.GetClaimsPrincipal()) .Calling(c => c.AuthorizedAction()) .ShouldReturn() .NotFound(); var controllerUser = controllerBuilder.AndProvideTheController().User; Assert.AreEqual("CustomUser", controllerUser.Identity.Name); Assert.AreEqual(null, controllerUser.Identity.AuthenticationType); Assert.IsFalse(controllerUser.Identity.IsAuthenticated); }
public void ToShouldResolveCorrectyWithFormUrlEncodedContentAndQueryString() { MyWebApi .Routes() .ShouldMap("api/Route/PostMethodWithQueryStringAndModel?value=test") .WithHttpMethod(HttpMethod.Post) .WithFormUrlEncodedContent("Integer=1&RequiredString=Test&NonRequiredString=AnotherTest&NotValidateInteger=2") .To <RouteController>(c => c.PostMethodWithQueryStringAndModel( "test", new RequestModel { Integer = 1, RequiredString = "Test", NonRequiredString = "AnotherTest", NotValidateInteger = 2 })); }
public void LinkGenerationShouldWorkCorrectlyWithCustomBaseAddress() { MyWebApi .IsUsingDefaultHttpConfiguration() .WithInlineConstraintResolver(TestObjectFactory.GetCustomInlineConstraintResolver()) .WithBaseAddress("http://mytestedasp.net"); MyWebApi .Controller <WebApiController>() .Calling(c => c.WithGeneratedLink(1)) .ShouldReturn() .Created() .AtLocation("http://mytestedasp.net/api/test?id=1"); RemoteServer.DisposeGlobal(); MyWebApi.IsUsing(TestObjectFactory.GetHttpConfigurationWithRoutes()); }
public static void Initialize(TestContext cont) { modelFactory = new ResponseModelFactory(); modelFactory.MapBothWays <Country, CountryResponseModel>(); modelFactory.MapBothWays <UserRating, HitmanRatingResponseModel>(); modelFactory.MapBothWays <Image, ImageResponseModel>(); modelFactory.MapBothWays <User, UserResponseModel>(); modelFactory.MapBothWays <UserRating, UserRatingResponseModel>(); Mapper.CreateMap <Contract, ContractResponseModel>() .ForMember(c => c.HitmanId, opts => opts.MapFrom(c => c.HitmanId)) .ForMember(c => c.ClientId, opts => opts.MapFrom(c => c.ClientId)) .ForMember(c => c.Status, opts => opts.MapFrom(c => (int)c.Status)); MyWebApi.IsRegisteredWith(WebApiConfig.Register); }
public void ShouldHavePostAttribute() { var member = new Membership(12) { Id = 0, FkHotel = 9, Price = 1200.000M }; // tests whether action has specific attribute type MyWebApi .Controller <MembershipController>() .Calling(c => c.Post(member)) .ShouldHave() .ActionAttributes(attributes => attributes .ContainingAttributeOfType <HttpPostAttribute>()); }
public void CallingShouldHaveValidModelStateWhenThereAreNoModelErrors() { var requestModel = TestObjectFactory.GetValidRequestModel(); var controller = MyWebApi .Controller <WebApiController>() .Calling(c => c.OkResultActionWithRequestBody(1, requestModel)) .ShouldReturn() .Ok() .AndProvideTheController(); var modelState = controller.ModelState; Assert.IsTrue(modelState.IsValid); Assert.AreEqual(0, modelState.Values.Count); Assert.AreEqual(0, modelState.Keys.Count); }
public void ContainingContentHeadersShouldNotThrowExceptionWithCorrectDictionaryOfHeadersWithInvalidCount() { MyWebApi .Controller <WebApiController>() .Calling(c => c.HttpResponseMessageAction()) .ShouldReturn() .HttpResponseMessage() .ContainingContentHeaders(new Dictionary <string, IEnumerable <string> > { { "TestHeader", new List <string> { "TestHeaderValue" } }, { "AnotherTestHeader", new List <string> { "TestHeaderValue" } } }); }
public void GET_profiles_name_Should_Return_Named_User_Profile() { MyWebApi .Routes() .ShouldMap("api/profiles/Wizard") .To <ProfilesController>(c => c.GetProfileByName("Wizard")); MyWebApi .Controller <ProfilesController>() .WithTestRig(rig) .WithAuthenticatedUser(rig.WizardUser()) .Calling(c => c.GetProfileByName("Wizard")) .ShouldReturn() .Ok() .WithResponseModelOfType <ProfileDto>() .Passing(dto => dto.Name == "Wizard" && dto.Uri.EndsWith("/api/profiles/Wizard")); }
public void ImagesUploadingShouldMapToCorrectMethod() { var imageRequestModel = new ImageRequestModel() { Name = "rabbit", Extension = "png", UserId = "d1f526fa-321d-4c4f-91fd-7c188bcf3cbc", Data = "{imageAsBase64}" }; MyWebApi .Routes() .ShouldMap("api/Images/") .WithHttpMethod(HttpMethod.Post) .WithJsonContent(JsonConvert.SerializeObject(imageRequestModel)) .To <ImagesController>(c => c.Post(imageRequestModel)); }
public void HttpServerTestShouldWorkCorrectlyWhenNoGlobalServerIsRunning() { Assert.IsFalse(OwinTestServer.GlobalIsStarted); Assert.IsFalse(HttpTestServer.GlobalIsStarted); MyWebApi .Server() .Working() .WithHttpRequestMessage( req => req.WithMethod(HttpMethod.Post).WithRequestUri("api/NoAttributes/WithParameter/5")) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.OK) .AndAlso() .WithResponseModelOfType <int>(); Assert.IsFalse(OwinTestServer.GlobalIsStarted); Assert.IsFalse(HttpTestServer.GlobalIsStarted); }
public static void Initialize(TestContext testContext) { NinjectConfig.DependenciesRegistration = kernel => { kernel.Bind(typeof(IRepository <User>)).ToConstant(Repositories.GetUsersRepository()); kernel.Bind(typeof(IRepository <RealEstate>)).ToConstant(Repositories.GetRealEstatesRepository()); kernel.Bind(typeof(IRepository <Comment>)).ToConstant(Repositories.GetCommentsRepository()); }; AutoMapperConfig.RegisterMappings(Assemblies.WebApi); var config = new HttpConfiguration(); WebApiConfig.Register(config); MyWebApi.IsUsing(config); }
public void WithContentHeaderAndMultipleValuesShouldPopulateCorrectHeader() { var headers = new[] { TestHeaderValue, AnotherTestHeaderValue }; var httpRequestMessage = MyWebApi .Controller <WebApiController>() .WithHttpRequestMessage(request => request .WithStringContent(StringContent) .WithContentHeader(TestHeader, headers)) .AndProvideTheHttpRequestMessage(); Assert.IsTrue(httpRequestMessage.Content.Headers.Contains(TestHeader)); Assert.IsTrue(httpRequestMessage.Content.Headers.First(h => h.Key == TestHeader).Value.Contains(TestHeaderValue)); Assert.IsTrue(httpRequestMessage.Content.Headers.First(h => h.Key == TestHeader).Value.Contains(AnotherTestHeaderValue)); }
public void Initialize() { userManager = new UserManager(new UserRepository(new EFDbContext(ContextEnum.BeatBuddyTest))); organisationManager = new OrganisationManager(new OrganisationRepository(new EFDbContext(ContextEnum.BeatBuddyTest))); user = userManager.CreateUser("*****@*****.**", "matthias", "test", "acidshards", ""); _organisationControllerWithAuthenticatedUser = MyWebApi.Controller <OrganisationsController>() .WithResolvedDependencyFor <IUserManager>(userManager) .WithResolvedDependencyFor <IOrganisationManager>(organisationManager) .WithAuthenticatedUser( u => u.WithIdentifier("NewId") .WithUsername(user.Email) .WithClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Email, user.Email)) .WithClaim(new System.Security.Claims.Claim("sub", user.Email)) ); organisation = organisationManager.CreateOrganisation("testorganisatie", "", user); }
public void WithHttpConfigurationShouldOverrideTheDefaultOne() { var config = new HttpConfiguration(); var controllerConfig = MyWebApi .Controller <WebApiController>() .WithHttpConfiguration(config) .AndProvideTheController() .Configuration; var controllerConfigFromApi = MyWebApi .Controller <WebApiController>() .WithHttpConfiguration(config) .AndProvideTheHttpConfiguration(); Assert.AreSame(config, controllerConfig); Assert.AreSame(config, controllerConfigFromApi); }
public void WithAuthenticatedUserShouldPopulateUserPropertyWithDefaultValues() { var controllerBuilder = MyWebApi .Controller <WebApiController>() .WithAuthenticatedUser(); controllerBuilder .Calling(c => c.AuthorizedAction()) .ShouldReturn() .Ok(); var controllerUser = controllerBuilder.AndProvideTheController().User; Assert.AreEqual(false, controllerUser.IsInRole("Any")); Assert.AreEqual("TestUser", controllerUser.Identity.Name); Assert.AreEqual("Passport", controllerUser.Identity.AuthenticationType); Assert.AreEqual(true, controllerUser.Identity.IsAuthenticated); }
public void CallingShouldPopulateModelStateWhenThereAreModelErrors() { var requestModel = TestObjectFactory.GetRequestModelWithErrors(); var controller = MyWebApi .Controller <WebApiController>() .Calling(c => c.OkResultActionWithRequestBody(1, requestModel)) .ShouldReturn() .Ok() .AndProvideTheController(); var modelState = controller.ModelState; Assert.IsFalse(modelState.IsValid); Assert.AreEqual(2, modelState.Values.Count); Assert.AreEqual("Integer", modelState.Keys.First()); Assert.AreEqual("RequiredString", modelState.Keys.Last()); }
public void HttpTestsShouldWorkCorrectlyWithGlobalTestServer() { MyWebApi.Server().Starts(); var request = new HttpRequestMessage(HttpMethod.Post, "/test"); MyWebApi .Server() .Working() .WithHttpRequestMessage(request) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.NotFound); MyWebApi .Server() .Working() .WithHttpRequestMessage(req => req.WithMethod(HttpMethod.Post).WithRequestUri("api/NoAttributes/WithParameter/5")) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.OK) .AndAlso() .WithResponseModelOfType <int>() .Passing(m => m == 5); MyWebApi .Server() .Working() .WithHttpRequestMessage(req => req .WithMethod(HttpMethod.Post) .WithRequestUri("api/NoAttributes/WithCookies") .WithHeader(HttpHeader.Cookie, "cookiename=cookievalue;anothercookie=anothervalue")) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.OK) .AndAlso() .WithStringContent("\"cookiename+cookievalue!anothercookie+anothervalue\""); MyWebApi .Server() .Working() .WithHttpRequestMessage(new HttpRequestMessage(HttpMethod.Post, "/Invalid")) .ShouldReturnHttpResponseMessage() .WithStatusCode(HttpStatusCode.NotFound); MyWebApi.Server().Stops(); }
public void CreateEmployee() { var request = new CreateEmployeeRequest { Fullname = "TesteUser", PreferedName = "User", Telephone = "07987979", Email = "*****@*****.**", IsLive = true }; MyWebApi .Routes() .ShouldMap("api/employee/createemployee") .WithHttpMethod(HttpMethod.Post) .WithJsonContent(@"{""Fullname"":""TesteUser"",""PreferedName"":""User"", ""Telephone"":""07987979"",""Email"":""*****@*****.**"", ""isLive"":true}") .To <EmployeeController>(c => c.CreateEmployee(request)) .ToInvalidModelState(); }
public void ToShouldThrowExceptionWithWrongActionArguments() { MyWebApi .Routes() .ShouldMap("api/Route/PostMethodWithQueryStringAndModel?value=test") .WithHttpMethod(HttpMethod.Post) .And() .WithJsonContent( @"{""Integer"": 1, ""RequiredString"": ""Test"", ""NonRequiredString"": ""AnotherTest"", ""NotValidateInteger"": 2}") .To <RouteController>(c => c.PostMethodWithQueryStringAndModel( "test", new RequestModel { Integer = 1, RequiredString = "Test2", NonRequiredString = "AnotherTest", NotValidateInteger = 2 })); }