Example #1
0
 public void WithResolvedDependencyForShouldChooseCorrectConstructorWithAllDependencies()
 {
     MyMvc
     .Controller <MvcController>()
     .WithServiceFor <IAnotherInjectedService>(new AnotherInjectedService())
     .WithServiceFor <RequestModel>(new RequestModel())
     .WithServiceFor <IInjectedService>(new InjectedService())
     .ShouldPassFor()
     .TheController(controller =>
     {
         Assert.NotNull(controller);
         Assert.NotNull(controller.InjectedService);
         Assert.NotNull(controller.AnotherInjectedService);
         Assert.NotNull(controller.InjectedRequestModel);
     });
 }
Example #2
0
 public void WithResolvedDependencyForShouldThrowExceptionWhenNoConstructorExistsForDependenciesForPocoController()
 {
     Test.AssertException <UnresolvedServicesException>(
         () =>
     {
         MyMvc
         .Controller <NoParameterlessConstructorController>()
         .WithServiceFor <RequestModel>(new RequestModel())
         .WithServiceFor <IAnotherInjectedService>(new AnotherInjectedService())
         .WithServiceFor <ResponseModel>(new ResponseModel())
         .Calling(c => c.OkAction())
         .ShouldReturn()
         .Ok();
     },
         "NoParameterlessConstructorController could not be instantiated because it contains no constructor taking RequestModel, AnotherInjectedService, ResponseModel as parameters.");
 }
Example #3
0
 public void WithControllerContextSetupShouldSetCorrectControllerContext()
 {
     MyMvc
     .Controller <MvcController>()
     .WithControllerContext(controllerContext =>
     {
         controllerContext.RouteData.Values.Add("testkey", "testvalue");
     })
     .ShouldPassFor()
     .TheController(controller =>
     {
         Assert.NotNull(controller);
         Assert.NotNull(controller.ControllerContext);
         Assert.True(controller.ControllerContext.RouteData.Values.ContainsKey("testkey"));
     });
 }
        public void ContainingOutputFormatterShouldThrowExceptionWithIncorrectValue()
        {
            Test.AssertException <OkResultAssertionException>(
                () =>
            {
                var formatter = TestObjectFactory.GetOutputFormatter();

                MyMvc
                .Controller <MvcController>()
                .Calling(c => c.OkActionWithFormatter(formatter))
                .ShouldReturn()
                .Ok()
                .ContainingOutputFormatter(new JsonOutputFormatter());
            },
                "When calling OkActionWithFormatter action in MvcController expected OK result output formatters to contain the provided formatter, but such was not found.");
        }
Example #5
0
 public void ContainingOutputFormattersShouldThrowExceptionWithIncorrectCount()
 {
     Test.AssertException <NotFoundResultAssertionException>(
         () =>
     {
         MyMvc
         .Controller <MvcController>()
         .Calling(c => c.FullHttpNotFoundAction())
         .ShouldReturn()
         .NotFound()
         .ContainingOutputFormatters(new List <IOutputFormatter>
         {
             new JsonOutputFormatter()
         });
     },
         "When calling FullHttpNotFoundAction action in MvcController expected HTTP not found result output formatters to have 1 item, but instead found 2.");
 }
        public void WithRequestShouldNotWorkWithDefaultRequestActionForPocoController()
        {
            MyMvc
            .IsUsingDefaultConfiguration()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            MyMvc
            .Controller <FullPocoController>()
            .Calling(c => c.WithRequest())
            .ShouldReturn()
            .BadRequest();

            MyMvc.IsUsingDefaultConfiguration();
        }
        public void CallingShouldPopulateCorrectActionNameWithTaskActionCallForPocoController()
        {
            MyMvc
            .IsUsingDefaultConfiguration()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            var voidActionResultTestBuilder = MyMvc
                                              .Controller <FullPocoController>()
                                              .Calling(c => c.EmptyActionAsync());

            this.CheckActionName(voidActionResultTestBuilder, "EmptyActionAsync");

            MyMvc.IsUsingDefaultConfiguration();
        }
 public void ContainingOutputFormattersShouldThrowExceptionWithIncorrectCount()
 {
     Test.AssertException <StatusCodeResultAssertionException>(
         () =>
     {
         MyMvc
         .Controller <MvcController>()
         .Calling(c => c.FullObjectResultAction())
         .ShouldReturn()
         .StatusCode()
         .ContainingOutputFormatters(new List <IOutputFormatter>
         {
             TestObjectFactory.GetOutputFormatter()
         });
     },
         "When calling FullObjectResultAction action in MvcController expected status code result output formatters to have 1 item, but instead found 2.");
 }
        public void WithModelShouldThrowExceptionWithIncorrectModel()
        {
            Test.AssertException <ResponseModelAssertionException>(
                () =>
            {
                var model             = TestObjectFactory.GetListOfResponseModels();
                model[0].IntegerValue = int.MaxValue;

                MyMvc
                .Controller <MvcController>()
                .Calling(c => c.IndexView())
                .ShouldReturn()
                .View("Index")
                .WithModel(model);
            },
                "When calling IndexView action in MvcController expected response model List<ResponseModel> to be the given model, but in fact it was a different one.");
        }
Example #10
0
        public void AndModelStateErrorShouldThrowExceptionWhenTheProvidedModelStateErrorDoesNotExist()
        {
            var requestBody = TestObjectFactory.GetValidRequestModel();

            Test.AssertException <ModelErrorAssertionException>(
                () =>
            {
                MyMvc
                .Controller <MvcController>()
                .Calling(c => c.ModelStateCheck(requestBody))
                .ShouldReturn()
                .Ok()
                .WithResponseModel(requestBody)
                .ContainingError("Name");
            },
                "When calling ModelStateCheck action in MvcController expected to have a model error against key Name, but none found.");
        }
Example #11
0
        public void CallingShouldWorkCorrectlyWithFromServices()
        {
            MyMvc
            .IsUsingDefaultConfiguration()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            MyMvc
            .Controller <MvcController>()
            .Calling(c => c.WithService(From.Services <IHttpContextAccessor>()))
            .ShouldReturn()
            .Ok();

            MyMvc.IsUsingDefaultConfiguration();
        }
        public void GetAvailableEmployees_WhenNoEmployees_ReturnsNoContent()
        {
            var employeeServiceMock = new Mock <IEmployeeService>();

            employeeServiceMock.Setup(es => es.GetAvailableEmployees(It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .ReturnsAsync((false, Enumerable.Empty <Employee>()));

            var request = _fixture.Create <AvailableEmployeesRequest>();

            MyMvc
            .Controller <EmployeeController>(instance => instance
                                             .WithDependencies(employeeServiceMock.Object)
                                             )
            .Calling(c => c.GetEmployees(request))
            .ShouldReturn()
            .NoContent();
        }
        public void MemoryCacheWithNumberShouldNotThrowExceptionWithCorrectCacheEntries()
        {
            MyMvc
            .IsUsingDefaultConfiguration()
            .WithServices(services => services.AddMemoryCache());

            MyMvc
            .Controller <MvcController>()
            .Calling(c => c.AddMemoryCacheAction())
            .ShouldHave()
            .MemoryCache(withNumberOfEntries: 2)
            .AndAlso()
            .ShouldReturn()
            .Ok();

            MyMvc.IsUsingDefaultConfiguration();
        }
        public void NoMemoryCacheShouldNotThrowExceptionWithNoCacheEntries()
        {
            MyMvc
            .IsUsingDefaultConfiguration()
            .WithServices(services => services.AddMemoryCache());

            MyMvc
            .Controller <MvcController>()
            .Calling(c => c.Ok())
            .ShouldHave()
            .NoMemoryCache()
            .AndAlso()
            .ShouldReturn()
            .Ok();

            MyMvc.IsUsingDefaultConfiguration();
        }
 public void PostAddWithInvalidDataShouldHaveModelErrors()
 => MyMvc
 .Controller <CreditCompaniesController>()
 .Calling(c => c.Add(new CreditCompanyCreateInputModel
 {
     Name         = string.Empty,
     ActiveSincce = DateTime.Now.AddDays(1),
 }))
 .ShouldHave()
 .ModelState(modelState => modelState
             .For <CreditCompanyCreateInputModel>()
             .ContainingErrorFor(m => m.Name)
             .AndAlso()
             .ContainingErrorFor(m => m.ActiveSincce))
 .AndAlso()
 .ShouldReturn()
 .View();
Example #16
0
 public void AndProvideTheModelShouldReturnProperModelWhenThereIsResponseModelWithModelStateErrorAndErrorCheck()
 {
     MyMvc
     .Controller <MvcController>()
     .Calling(c => c.CustomModelStateError())
     .ShouldReturn()
     .Ok()
     .WithResponseModelOfType <ICollection <ResponseModel> >()
     .ContainingError("Test").ThatEquals("Test error")
     .ShouldPassFor()
     .TheModel(responseModel =>
     {
         Assert.NotNull(responseModel);
         Assert.IsAssignableFrom <List <ResponseModel> >(responseModel);
         Assert.Equal(2, responseModel.Count);
     });
 }
Example #17
0
        public void ContainingNoErrorsShouldThrowExceptionWhenThereAreModelStateErrors()
        {
            var requestBodyWithErrors = TestObjectFactory.GetRequestModelWithErrors();

            Test.AssertException <ModelErrorAssertionException>(
                () =>
            {
                MyMvc
                .Controller <MvcController>()
                .Calling(c => c.OkResultActionWithRequestBody(1, requestBodyWithErrors))
                .ShouldReturn()
                .Ok()
                .WithResponseModelOfType <ICollection <ResponseModel> >()
                .ContainingNoErrors();
            },
                "When calling OkResultActionWithRequestBody action in MvcController expected to have valid model state with no errors, but it had some.");
        }
 public void WithLocationShouldSetCorrectProperties()
 {
     MyMvc
     .Controller <MvcController>()
     .WithHttpRequest(request => request.WithLocation("https://mytestesasp.net:1337/api/Projects/MyTested.AspNetCore.Mvc?version=1.0"))
     .ShouldPassFor()
     .TheHttpRequest(builtRequest =>
     {
         Assert.Equal("mytestesasp.net:1337", builtRequest.Host.Value);
         Assert.Equal("/api/Projects/MyTested.AspNetCore.Mvc", builtRequest.Path);
         Assert.Equal("/api/Projects/MyTested.AspNetCore.Mvc", builtRequest.PathBase);
         Assert.Equal("?version=1.0", builtRequest.QueryString.Value);
         Assert.Equal(1, builtRequest.Query.Count);
         Assert.Equal("1.0", builtRequest.Query["version"]);
         Assert.Equal("https", builtRequest.Scheme);
     });
 }
Example #19
0
 public void AndProvideTheModelShouldReturnProperModelWhenThereIsResponseModelWithPassing()
 {
     MyMvc
     .Controller <MvcController>()
     .Calling(c => c.OkResultWithResponse())
     .ShouldReturn()
     .Ok()
     .WithResponseModelOfType <List <ResponseModel> >()
     .Passing(m => m.Count == 2)
     .ShouldPassFor()
     .TheModel(responseModel =>
     {
         Assert.NotNull(responseModel);
         Assert.IsAssignableFrom <List <ResponseModel> >(responseModel);
         Assert.Equal(2, responseModel.Count);
     });
 }
 public void WithLocationAsBuilderShouldThrowExceptionWithIncorrectQuery()
 {
     Test.AssertException <ArgumentException>(
         () =>
     {
         MyMvc
         .Controller <MvcController>()
         .WithHttpRequest(request => request
                          .WithLocation(location => location
                                        .WithHost("mytestesasp.net")
                                        .WithPort(1337)
                                        .WithScheme("https")
                                        .WithAbsolutePath("api/Projects/MyTested.AspNetCore.Mvc")
                                        .WithQuery("version=1.0")));
     },
         "Query string must start with the '?' symbol.");
 }
 public void ContainingContentTypesAsStringValueShouldNotThrowExceptionWithIncorrectCount()
 {
     Test.AssertException <StatusCodeResultAssertionException>(
         () =>
     {
         MyMvc
         .Controller <MvcController>()
         .Calling(c => c.FullObjectResultAction())
         .ShouldReturn()
         .StatusCode()
         .ContainingContentTypes(new List <string>
         {
             ContentType.ApplicationXml
         });
     },
         "When calling FullObjectResultAction action in MvcController expected status code result content types to have 1 item, but instead found 2.");
 }
Example #22
0
 public void DetailsShouldReturnViewWithCorrectValues()
 => MyMvc
 .Controller <ProductsController>()
 .WithData(db => db
           .WithSet <Product>(set => set.Add(this.CreateTestProduct())))
 .Calling(c => c.Details(Id))
 .ShouldReturn()
 .View(view => view
       .WithModelOfType <ProductDetailsViewModel>()
       .Passing(model =>
 {
     Assert.Equal(Name, model.Name);
     Assert.Equal(ImageUrl, model.ImageUrl);
     Assert.Equal(Price, model.Price);
     Assert.Equal(InStock, model.InStock);
     Assert.Equal(Type, model.TypeName);
 }));
        public void CallingShouldPopulateCorrectActionNameAndActionResultWithNormalActionCallForPocoController()
        {
            MyMvc
            .IsUsingDefaultConfiguration()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            var actionResultTestBuilder = MyMvc
                                          .Controller <FullPocoController>()
                                          .Calling(c => c.OkResultAction());

            this.CheckActionResultTestBuilder(actionResultTestBuilder, "OkResultAction");

            MyMvc.IsUsingDefaultConfiguration();
        }
Example #24
0
 public void DeleteShouldBeOnlyForAdminsAndShouldRedirectToHomePageWhenSucceeded()
 => MyMvc
 .Controller <ProductsController>()
 .WithData(db => db
           .WithSet <Product>(set => set.Add(this.CreateTestProduct())))
 .Calling(c => c.Delete(Id))
 .ShouldHave()
 .ActionAttributes(attrs => attrs
                   .RestrictingForAuthorizedRequests(GlobalConstants.AdministratorRoleName))
 .AndAlso()
 .ShouldHave()
 .Data(db => db
       .WithSet <Product>(set => set.Count() == 0))
 .AndAlso()
 .ShouldReturn()
 .Redirect(/*redirect => redirect
            * .To<HomeController>(c => c.Index(With.Any<string>(), With.Any<bool>()))*/);
        public void WithResolvedDependencyForShouldChooseCorrectConstructorWithMoreDependenciesForPocoController()
        {
            MyMvc
            .Controller <FullPocoController>()
            .WithServiceFor <IAnotherInjectedService>(new AnotherInjectedService())
            .WithServiceFor <IInjectedService>(new InjectedService())
            .ShouldPassFor()
            .TheController(controller =>
            {
                Assert.NotNull(controller);
                Assert.NotNull(controller.InjectedService);
                Assert.NotNull(controller.AnotherInjectedService);
                Assert.Null(controller.InjectedRequestModel);
            });

            MyMvc.IsUsingDefaultConfiguration();
        }
 public void WithItemsShouldThrowExceptionWithInvalidCount()
 {
     Test.AssertException <AuthenticationPropertiesAssertionException>(
         () =>
     {
         MyMvc
         .Controller <MvcController>()
         .Calling(c => c.ChallengeWithAuthenticationProperties())
         .ShouldReturn()
         .Challenge()
         .WithAuthenticationProperties(auth => auth.WithItems(new Dictionary <string, string>
         {
             { "TestKeyItem", "TestValueItem" }
         }));
     },
         "When calling ChallengeWithAuthenticationProperties action in MvcController expected authentication properties to have 1 custom item, but in fact found 2.");
 }
Example #27
0
 public void ContainingContentTypesAsMediaTypeHeaderValueShouldNotThrowExceptionWithIncorrectCount()
 {
     Test.AssertException <NotFoundResultAssertionException>(
         () =>
     {
         MyMvc
         .Controller <MvcController>()
         .Calling(c => c.FullHttpNotFoundAction())
         .ShouldReturn()
         .NotFound()
         .ContainingContentTypes(new List <MediaTypeHeaderValue>
         {
             new MediaTypeHeaderValue(ContentType.ApplicationXml)
         });
     },
         "When calling FullHttpNotFoundAction action in MvcController expected HTTP not found result content types to have 1 item, but instead found 2.");
 }
Example #28
0
        public void AndNoModelStateErrorForShouldThrowExceptionWhenTheProvidedPropertyHasErrors()
        {
            var requestBodyWithErrors = TestObjectFactory.GetRequestModelWithErrors();

            Test.AssertException <ModelErrorAssertionException>(
                () =>
            {
                MyMvc
                .Controller <MvcController>()
                .Calling(c => c.ModelStateCheck(requestBodyWithErrors))
                .ShouldReturn()
                .Ok()
                .WithResponseModel(requestBodyWithErrors)
                .ContainingNoErrorFor(r => r.RequiredString);
            },
                "When calling ModelStateCheck action in MvcController expected to have no model errors against key RequiredString, but found some.");
        }
        public void ControllerWithNoParameterlessConstructorAndNoServicesShouldThrowProperException()
        {
            MyMvc.IsUsingDefaultConfiguration();

            Test.AssertException <UnresolvedServicesException>(
                () =>
            {
                MyMvc
                .Controller <NoParameterlessConstructorController>()
                .Calling(c => c.OkAction())
                .ShouldReturn()
                .Ok();
            },
                "NoParameterlessConstructorController could not be instantiated because it contains no constructor taking no parameters.");

            MyMvc.IsUsingDefaultConfiguration();
        }
Example #30
0
 public void WithSessionShouldThrowExceptionIfSessionIsNotSetForPocoController()
 {
     Test.AssertException <InvalidOperationException>(
         () =>
     {
         MyMvc
         .Controller <PocoController>()
         .WithSession(session =>
         {
             session.WithEntry("test", "value");
         })
         .Calling(c => c.SessionAction())
         .ShouldReturn()
         .Ok();
     },
         "Session has not been configured for this application or request.");
 }