public void ContainingOutputFormattersShouldThrowExceptionWithIncorrectValue() { Test.AssertException <CreatedResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullCreatedAction()) .ShouldReturn() .Created() .ContainingOutputFormatters(new List <IOutputFormatter> { new JsonOutputFormatter(), new HttpNotAcceptableOutputFormatter() }); }, "When calling FullCreatedAction action in MvcController expected created result output formatters to contain formatter of HttpNotAcceptableOutputFormatter type, but none was found."); }
public void ContainingContentTypesAsMediaTypeHeaderValueShouldNotThrowExceptionWithIncorrectValue() { Test.AssertException <NotFoundResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullHttpNotFoundAction()) .ShouldReturn() .NotFound() .ContainingContentTypes(new List <MediaTypeHeaderValue> { new MediaTypeHeaderValue(ContentType.ApplicationOctetStream), new MediaTypeHeaderValue(ContentType.ApplicationXml) }); }, "When calling FullHttpNotFoundAction action in MvcController expected HTTP not found result content types to contain application/octet-stream, but none was found."); }
public void CreateShouldHaveAuthorizeAndHttpPostAttributesShouldRedirectToAllWhenModelStateIsValid() => MyMvc .Controller <JobsController>(instance => instance .WithUser()) .Calling(c => c.Create(GetValidJobInputModel())) .ShouldHave() .ActionAttributes(a => a .ContainingAttributeOfType <AuthorizeAttribute>()) .AndAlso() .ShouldHave() .ActionAttributes(a => a. ContainingAttributeOfType <HttpPostAttribute>()) .AndAlso() .ShouldHave() .ValidModelState() .AndAlso() .ShouldReturn() .RedirectToAction("All");
public void ContainingContentTypesStringValueShouldNotThrowExceptionWithIncorrectValue() { Test.AssertException <CreatedResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullCreatedAction()) .ShouldReturn() .Created() .ContainingContentTypes(new List <string> { ContentType.ApplicationOctetStream, ContentType.ApplicationXml }); }, "When calling FullCreatedAction action in MvcController expected created result content types to contain application/octet-stream, but none was found."); }
public void ToShouldWorkCorrectly() { MyMvc.StartsFrom <RoutesStartup>(); Test.AssertException <RedirectResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.LocalRedirectActionWithCustomUrlHelper(null)) .ShouldReturn() .LocalRedirect() .To <NoAttributesController>(c => c.WithParameter(1)); }, "When calling LocalRedirectActionWithCustomUrlHelper action in MvcController expected local redirect result to have resolved location to '/api/Redirect/WithParameter?id=1', but in fact received '/api/test'."); MyMvc.IsUsingDefaultConfiguration(); }
public void PrepareControllerShouldSetCorrectPropertiesWithCustomSetup() { MyMvc .Controller <MvcController>() .WithSetup(c => { c.ControllerContext = new ControllerContext(); }) .ShouldPassFor() .TheController(controller => { Assert.NotNull(controller); Assert.NotNull(controller.ControllerContext); Assert.Null(controller.ControllerContext.HttpContext); Assert.Empty(controller.ControllerContext.InputFormatters); Assert.Empty(controller.ControllerContext.ValidatorProviders); }); }
public void WithAuthenticatedNotCalledShouldNotHaveAuthorizedUser() { MyMvc .Controller <MvcController>() .Calling(c => c.AuthorizedAction()) .ShouldReturn() .NotFound() .ShouldPassFor() .TheController(controller => { var controllerUser = (controller as Controller).User; Assert.Equal(false, controllerUser.IsInRole("Any")); Assert.Equal(null, controllerUser.Identity.Name); Assert.Equal(null, controllerUser.Identity.AuthenticationType); Assert.Equal(false, controllerUser.Identity.IsAuthenticated); }); }
public void ContainingOutputFormattersShouldThrowExceptionWithIncorrectValue() { Test.AssertException <NotFoundResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullHttpNotFoundAction()) .ShouldReturn() .NotFound() .ContainingOutputFormatters(new List <IOutputFormatter> { new StringOutputFormatter(), new CustomOutputFormatter() }); }, "When calling FullHttpNotFoundAction action in MvcController expected HTTP not found result output formatters to contain formatter of StringOutputFormatter type, but none was found."); }
public void AtShouldWorkCorrectlyWithCorrectTaskActionCall() { MyMvc.StartsFrom <RoutesStartup>(); Test.AssertException <RedirectResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.RedirectToRouteAction()) .ShouldReturn() .Redirect() .To <MvcController>(c => c.AsyncOkResultAction()); }, "When calling RedirectToRouteAction action in MvcController expected redirect result to have resolved location to '/api/test', but in fact received '/api/Redirect/WithParameter?id=1'."); MyMvc.IsUsingDefaultConfiguration(); }
/// <summary> /// Should return code 200 and an empty list of tag relations if called for an existing tag that has no relations /// </summary> // TODO [Test] public void GetRelationsForIdWithNoExistingRelationsTest() { // ReSharper disable once CollectionNeverUpdated.Local var expected = new List <AnnotationTagRelation>(); MyMvc .Controller <AnnotationController>() .WithAuthenticatedUser(user => user.WithClaim("Id", "1")) .WithDbContext(dbContext => dbContext .WithSet <User>(db => db.Add(_admin)) .WithSet <AnnotationTag>(db => db.AddRange(_tag1, _tag2)) ) .Calling(c => c.GetRelationsForId(_tag1.Id)) .ShouldReturn() .Ok() .WithModelOfType <List <AnnotationTagRelation> >() .Passing(actual => expected.SequenceEqual(actual)); }
public void GetAllowedRelationRulesForTagTest_NoToplevelRelation() { MyMvc .Controller <AnnotationController>() .WithAuthenticatedUser(user => user.WithClaim("Id", "1")) .WithDbContext(dbContext => dbContext .WithSet <User>(db => db.Add(_admin)) .WithSet <AnnotationTag>(db => db.AddRange(_tag1, _tag2, _tag3, _tag4)) .WithSet <Layer>(db => db.AddRange(_layer1, _layer2)) .WithSet <LayerRelationRule>(db => db.Add(_layerRelationRule)) ) // no layer relation rules exist from layer2 to layer1 --> no relations from tag2 to tag1 / tag3 allowed .Calling(c => c.GetAllowedRelationRulesForTag(_tag2.Id)) .ShouldReturn() .Ok() .WithModelOfType <List <AnnotationTag> >() .Passing(actual => !actual.Any()); }
public void UsingUrlHelperInsideControllerShouldWorkCorrectlyForPocoController() { MyMvc .IsUsingDefaultConfiguration() .WithServices(services => { services.AddHttpContextAccessor(); }); MyMvc .Controller <FullPocoController>() .WithRouteData() .Calling(c => c.UrlAction()) .ShouldReturn() .Ok() .WithResponseModel("/FullPoco/UrlAction"); MyMvc.IsUsingDefaultConfiguration(); }
public void WithAuthenticatedUserShouldPopulateProperUserWhenUserWithUserBuilderForPocoController() { MyMvc .IsUsingDefaultConfiguration() .WithServices(services => { services.AddHttpContextAccessor(); }); MyMvc .Controller <FullPocoController>() .WithAuthenticatedUser(user => user .WithUsername("NewUserName") .WithAuthenticationType("Custom") .InRole("NormalUser") .AndAlso() .InRoles("Moderator", "Administrator") .InRoles(new[] { "SuperUser", "MegaUser" })) .Calling(c => c.AuthorizedAction()) .ShouldReturn() .Ok() .ShouldPassFor() .TheController(controller => { var controllerUser = (controller as FullPocoController).CustomHttpContext.User; Assert.Equal("NewUserName", controllerUser.Identity.Name); Assert.Equal("Custom", controllerUser.Identity.AuthenticationType); Assert.Equal(true, controllerUser.Identity.IsAuthenticated); Assert.Equal(true, controllerUser.IsInRole("NormalUser")); Assert.Equal(true, controllerUser.IsInRole("Moderator")); Assert.Equal(true, controllerUser.IsInRole("Administrator")); Assert.Equal(true, controllerUser.IsInRole("SuperUser")); Assert.Equal(true, controllerUser.IsInRole("MegaUser")); Assert.Equal(false, controllerUser.IsInRole("AnotherRole")); }); MyMvc.IsUsingDefaultConfiguration(); }
public void ContainingOutputFormattersShouldThrowExceptionWithIncorrectCountWithMoreThanOneItem() { Test.AssertException <StatusCodeResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullObjectResultAction()) .ShouldReturn() .StatusCode() .ContainingOutputFormatters(new List <IOutputFormatter> { TestObjectFactory.GetOutputFormatter(), new CustomOutputFormatter(), TestObjectFactory.GetOutputFormatter() }); }, "When calling FullObjectResultAction action in MvcController expected status code result output formatters to have 3 items, but instead found 2."); }
public void ContainingContentTypesAsStringValueShouldNotThrowExceptionWithIncorrectCountWithMoreThanOneItem() { Test.AssertException <StatusCodeResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullObjectResultAction()) .ShouldReturn() .StatusCode() .ContainingContentTypes(new List <string> { ContentType.ApplicationXml, ContentType.ApplicationJson, ContentType.ApplicationZip }); }, "When calling FullObjectResultAction action in MvcController expected status code result content types to have 3 items, but instead found 2."); }
public void SalesShouldWorkCorrectly() { MyMvc .Pipeline() .ShouldMap(request => request .WithLocation("/Analyse/Sales") .WithMethod(HttpMethod.Get) .WithUser()) .To <AnalyseController>(c => c.Sales()) .Which() .ShouldHave() .ActionAttributes(attr => attr .RestrictingForAuthorizedRequests()) .ValidModelState() .AndAlso() .ShouldReturn() .View(result => result .WithModelOfType <SalesViewModel>()); }
public void WithoutHttpContextFactoryTheDefaultMockedHttpContextShouldBeProvided() { MyMvc.IsUsingDefaultConfiguration() .WithServices(services => { services.RemoveTransient <IHttpContextFactory>(); }); var httpContextFactory = TestServiceProvider.GetService <IHttpContextFactory>(); Assert.Null(httpContextFactory); var httpContext = TestHelper.CreateMockedHttpContext(); Assert.NotNull(httpContext); Assert.Equal(ContentType.FormUrlEncoded, httpContext.Request.ContentType); MyMvc.IsUsingDefaultConfiguration(); }
public void CreateShouldHaveAuthorizeAndHttpPostAttributesShouldReturnViewWhenModelStateIsNotValid() => MyMvc .Controller <ForumController>(instance => instance .WithUser()) .Calling(c => c.Create(new DiscussionInputModel())) .ShouldHave() .ActionAttributes(a => a .ContainingAttributeOfType <AuthorizeAttribute>()) .AndAlso() .ShouldHave() .ActionAttributes(a => a. ContainingAttributeOfType <HttpPostAttribute>()) .AndAlso() .ShouldHave() .InvalidModelState() .AndAlso() .ShouldReturn() .View(view => view. WithModelOfType <DiscussionInputModel>());
public void ContainingOutputFormattersShouldThrowExceptionWithIncorrectCountWithMoreThanOneItem() { Test.AssertException <NotFoundResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullHttpNotFoundAction()) .ShouldReturn() .NotFound() .ContainingOutputFormatters(new List <IOutputFormatter> { new JsonOutputFormatter(), new CustomOutputFormatter(), new JsonOutputFormatter() }); }, "When calling FullHttpNotFoundAction action in MvcController expected HTTP not found result output formatters to have 3 items, but instead found 2."); }
public void ThatEqualsShouldThrowExceptionWhenProvidedMessageIsValid() { var requestModelWithErrors = TestObjectFactory.GetRequestModelWithErrors(); Test.AssertException <ModelErrorAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.ModelStateCheck(requestModelWithErrors)) .ShouldHave() .ModelState(modelState => modelState.For <RequestModel>() .ContainingNoErrorFor(m => m.NonRequiredString) .AndAlso() .ContainingErrorFor(m => m.RequiredString).ThatEquals("RequiredString field is required.") .ContainingErrorFor(m => m.Integer).ThatEquals(string.Format("Integer must be between {0} and {1}.", 1, int.MaxValue))); }, "When calling ModelStateCheck action in MvcController expected error message for key RequiredString to be 'RequiredString field is required.', but instead found 'The RequiredString field is required.'."); }
public void ContainingContentTypesAsMediaTypeHeaderValueValueShouldNotThrowExceptionWithIncorrectCountWithMoreThanOneItem() { Test.AssertException <NotFoundResultAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.FullHttpNotFoundAction()) .ShouldReturn() .NotFound() .ContainingContentTypes(new List <MediaTypeHeaderValue> { new MediaTypeHeaderValue(ContentType.ApplicationXml), new MediaTypeHeaderValue(ContentType.ApplicationJson), new MediaTypeHeaderValue(ContentType.ApplicationZip) }); }, "When calling FullHttpNotFoundAction action in MvcController expected HTTP not found result content types to have 3 items, but instead found 2."); }
public void WithModelStateShouldThrowExceptionWhenModelStateHasDifferentKeys() { Test.AssertException <BadRequestResultAssertionException>( () => { var requestModelWithErrors = TestObjectFactory.GetRequestModelWithErrors(); var modelState = new ModelStateDictionary(); modelState.AddModelError("Integer", "The field Integer must be between 1 and 2147483647."); modelState.AddModelError("String", "The RequiredString field is required."); MyMvc .Controller <MvcController>() .Calling(c => c.BadRequestWithModelState(requestModelWithErrors)) .ShouldReturn() .BadRequest() .WithModelStateError(modelState); }, "When calling BadRequestWithModelState action in MvcController expected bad request model state dictionary to contain String key, but none found."); }
public void ContainingHeadersWithHeadersDictionaryShouldThrowExceptionWithInvalidCount() { var headers = new HeaderDictionary { ["Set-Cookie"] = new[] { "TestCookie=TestCookieValue; expires=Thu, 31 Dec 2015 23:01:01 GMT; domain=testdomain.com; path=/; secure; httponly", "AnotherCookie=TestCookieValue; expires=Thu, 31 Dec 2015 23:01:01 GMT; domain=testdomain.com; path=/; secure; httponly" }, }; Test.AssertException <HttpResponseAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.CustomVoidResponseAction()) .ShouldHave() .HttpResponse(response => response.ContainingHeaders(headers)); }, "When calling CustomVoidResponseAction action in MvcController expected HTTP response headers to have 1 item, but instead found 6."); }
public void RemoveAlbumConfirmedShouldReturnNotFoundCalledWithNotExistingAlbumId() { var albums = CreateTestAlbums(10); var albumId = -1; MyMvc .Controller <StoreManagerController>() .WithData(db => db .WithEntities(entities => { entities.AddRange(albums); })) .Calling(x => x.RemoveAlbumConfirmed( From.Services <IMemoryCache>(), albumId, CancellationToken.None)) .ShouldReturn() .NotFound(); }
public void CustomStartupWithAdditionalServiceShouldSetThem() { MyMvc.StartsFrom <CustomStartup>() .WithServices(services => { services.AddTransient <IAnotherInjectedService, AnotherInjectedService>(); }); var service = TestApplication.Services.GetRequiredService <IAnotherInjectedService>(); Assert.NotNull(service); var routes = TestApplication.Router as RouteCollection; Assert.NotNull(routes); Assert.Equal(2, routes.Count); MyMvc.IsUsingDefaultConfiguration(); }
public void ContainingEntriesShouldThrowExceptionWithIncorrectCount() { Test.AssertException <DataProviderAssertionException>( () => { MyMvc .Controller <MvcController>() .Calling(c => c.AddTempDataAction()) .ShouldHave() .TempData(tempData => tempData.ContainingEntries(new Dictionary <string, object> { ["Test"] = "TempValue", })) .AndAlso() .ShouldReturn() .Ok(); }, "When calling AddTempDataAction action in MvcController expected temp data to have 1 entry, but in fact found 2."); }
public void WithHttpContextFactoryShouldReturnMockedHttpContextBasedOnTheFactoryCreatedHttpContext() { MyMvc.IsUsingDefaultConfiguration() .WithServices(services => { services.ReplaceTransient <IHttpContextFactory, CustomHttpContextFactory>(); }); var httpContextFactory = TestServiceProvider.GetService <IHttpContextFactory>(); Assert.NotNull(httpContextFactory); var httpContext = TestHelper.CreateMockedHttpContext(); Assert.NotNull(httpContext); Assert.Equal(ContentType.AudioVorbis, httpContext.Request.ContentType); MyMvc.IsUsingDefaultConfiguration(); }
public void PostLoginShouldReturnRedirectToLocalWithValidUserNameAndReturnUrl() { var model = new LoginViewModel { Email = MockedSignInManager.ValidUser, Password = MockedSignInManager.ValidUser }; var returnUrl = "/Store/Index"; MyMvc .Controller <AccountController>() .Calling(c => c.Login( model, returnUrl)) .ShouldReturn() .Redirect() .ToUrl(returnUrl); }
public void PostAddressAndPaymentShouldHaveValidAttributes() { MyMvc .Controller <CheckoutController>() .Calling(c => c.AddressAndPayment( With.No <MusicStoreContext>(), With.Default <Order>(), CancellationToken.None)) .ShouldHave() .ActionAttributes(attrs => attrs .RestrictingForHttpMethod(HttpMethod.Post) .ValidatingAntiForgeryToken()) .AndAlso() .ShouldHave() .InvalidModelState() .AndAlso() .ShouldReturn() .View(With.Default <Order>()); }
public void PostLoginShouldReturnRedirectToActionWithValidUserName() { var model = new LoginViewModel { Email = MockedSignInManager.ValidUser, Password = MockedSignInManager.ValidUser }; MyMvc .Controller <AccountController>() .Calling(c => c.Login( model, With.No <string>())) .ShouldReturn() .Redirect() .To <HomeController>(c => c.Index( With.No <MusicStoreContext>(), With.No <IMemoryCache>())); }