public void CreateController_UsesControllerActivatorToInstantiateController() { // Arrange var expected = new MyController(); var actionDescriptor = new ControllerActionDescriptor { ControllerTypeInfo = typeof(MyController).GetTypeInfo() }; var httpContext = new DefaultHttpContext(); httpContext.RequestServices = GetServices(); var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor); var activator = new Mock<IControllerActivator>(); activator.Setup(a => a.Create(actionContext, typeof(MyController))) .Returns(expected) .Verifiable(); var controllerFactory = new DefaultControllerFactory(activator.Object); // Act var result = controllerFactory.CreateController(actionContext); // Assert var controller = Assert.IsType<MyController>(result); Assert.Same(expected, controller); activator.Verify(); }
public void Run() { var controller = new MyController(); var result = (ViewResult) controller.Index(); Console.WriteLine(result.ViewBag.MyDynamicValue); }
public void Test_RunOnAuthorization() { var controller = new MyController(); controller.CallInitialize(); Mvc3TestHelper.RunOnAuthorization(controller, "Action"); Assert.IsTrue(controller.OnAuthorizationCalled); Assert.IsTrue(controller.Attribute_OnAuthorizationCalled); }
public void DefaultControllerFactory_DisposesIDisposableController() { // Arrange var factory = new DefaultControllerFactory( Mock.Of<IServiceProvider>(), Mock.Of<ITypeActivator>(), Mock.Of<IControllerActivator>()); var controller = new MyController(); // Act + Assert Assert.False(controller.Disposed); factory.ReleaseController(controller); Assert.True(controller.Disposed); }
public void BeginPasswordReset_SendsEmail() { const string emailAddress = "*****@*****.**"; var sendCalled = new ManualResetEvent(false); var mockEmailService = new Mock<IEmailService>(); mockEmailService.Setup(m => m.Send(emailAddress)).Callback(() => { sendCalled.Set(); }); var controller = new MyController(mockEmailService.Object, new TestTaskScheduler()); controller.BeginPasswordReset(emailAddress); Assert.IsTrue(sendCalled.WaitOne(TimeSpan.FromSeconds(3)), "Send was never called"); mockEmailService.Verify(es => es.Send(emailAddress)); }
public void MockMemoryCacheShouldBeDifferentForEveryCallSynchronouslyWithCachedControllerBuilder() { MyApplication .StartsFrom<DefaultStartup>() .WithServices(services => services.AddMemoryCache()); var controller = new MyController<MvcController>(); // second call should not have cache entries controller .WithMemoryCache(cache => cache.WithEntry("test", "value")) .Calling(c => c.MemoryCacheAction()) .ShouldReturn() .Ok(); controller .Calling(c => c.MemoryCacheAction()) .ShouldReturn() .BadRequest(); MyApplication.StartsFrom<DefaultStartup>(); }
public void VoidActionShouldNotThrowExceptionWithCorrectResponse() { MyController <MvcController> .Instance() .Calling(c => c.CustomResponseAction()) .ShouldHave() .HttpResponse(response => response .WithContentType(ContentType.ApplicationJson) .AndAlso() .WithStatusCode(HttpStatusCode.InternalServerError) .AndAlso() .ContainingHeader("TestHeader", "TestHeaderValue") .ContainingCookie("TestCookie", "TestCookieValue", new CookieOptions { HttpOnly = true, Secure = true, Domain = "testdomain.com", Expires = new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc)), Path = "/" })) .AndAlso() .ShouldReturn() .Ok(); }
public void WithResponseCookieBuilderShouldNotThrowExceptionWithCorrectCookie() { MyController <MvcController> .Instance() .Calling(c => c.CustomVoidResponseAction()) .ShouldHave() .HttpResponse(response => response .ContainingCookie(cookie => cookie .WithName("TestCookie") .AndAlso() .WithValue("TestCookieValue") .AndAlso() .WithSecurity(true) .AndAlso() .WithHttpOnly(true) .AndAlso() .WithMaxAge(null) .AndAlso() .WithDomain("testdomain.com") .AndAlso() .WithExpiration(new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc))) .AndAlso() .WithPath("/"))); }
public void WithJsonSerializerSettingsShouldThrowExceptionWithActionSettings() { var jsonSettings = new JsonSerializerSettings { CheckAdditionalContent = true, NullValueHandling = NullValueHandling.Ignore }; Test.AssertException <JsonResultAssertionException>( () => { MyController <MvcController> .Instance() .Calling(c => c.JsonWithSpecificSettingsAction(jsonSettings)) .ShouldReturn() .Json(json => json .WithJsonSerializerSettings(settings => { settings.WithAdditionalContentChecking(false); settings.WithNullValueHandling(NullValueHandling.Ignore); })); }, "When calling JsonWithSpecificSettingsAction action in MvcController expected JSON result serializer settings to have disabled checking for additional content, but in fact it was enabled."); }
public void ContainingEntryWithOptionsShouldThrowExceptionWithIncorrectSlidingExpiration() { var cacheValue = new byte[] { 127, 127, 127 }; Test.AssertException <DataProviderAssertionException>( () => { MyController <MvcController> .Instance() .Calling(c => c.AddDistributedCacheAction()) .ShouldHave() .DistributedCache(cache => cache .ContainingEntry("test", cacheValue, new DistributedCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(new DateTime(2020, 1, 1, 1, 1, 1, DateTimeKind.Utc)), AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1), SlidingExpiration = TimeSpan.FromMinutes(3) })) .AndAlso() .ShouldReturn() .Ok(); }, "When calling AddDistributedCacheAction action in MvcController expected distributed cache to have entry with the given options, but in fact they were different."); }
public void WithMultipleLicensesNoExceptionShouldBeThrown() { MyApplication .StartsFrom <DefaultStartup>() .WithTestConfiguration(config => { config.AddJsonFile("multilicenseconfig.json"); }); LicenseValidator.ClearLicenseDetails(); TestCounter.SetLicenseData(null, DateTime.MinValue, "MyTested.AspNetCore.Mvc.Tests"); Task.Run(async() => { var tasks = new List <Task>(); for (int i = 0; i < 500; i++) { tasks.Add(Task.Run(() => { MyController <MvcController> .Instance() .Calling(c => c.OkResultAction()) .ShouldReturn() .Ok(); })); } await Task.WhenAll(tasks); }) .ConfigureAwait(false) .GetAwaiter() .GetResult(); MyApplication.StartsFrom <DefaultStartup>(); }
public void WithoutDataByProvidingNonExistingModelAndKeyInBuilderShouldRemoveTheCorrectObject() { MyApplication .StartsFrom <TestStartup>() .WithServices(services => services.AddDbContext <CustomDbContext>()); var model = new CustomModel { Id = 1, Name = "Test" }; var keyToRemove = int.MaxValue; MyController <DbContextController> .Instance() .WithData(model) .WithoutData(data => data.WithoutEntityByKey <CustomModel>(keyToRemove)) .Calling(c => c.Get(model.Id)) .ShouldReturn() .Ok(ok => ok .WithModelOfType <CustomModel>() .Passing(cm => cm.Name.Equals(model.Name))); }
public void EditShouldHaveAuthorizeAndHttpPostAttributesAndShouldReturnEditViewModelWhenThemodelStateIsInvalid(int id) => MyController <ProjectsController> .Instance() .WithUser(u => u.WithIdentifier(UserId)) .WithData( GetUser(), GetProject()) .Calling(c => c.Edit(id, new EditProjectInputModul { Id = 1 })) .ShouldHave() .ActionAttributes(a => a .ContainingAttributeOfType <AuthorizeAttribute>()) .AndAlso() .ShouldHave() .ActionAttributes(a => a. ContainingAttributeOfType <HttpPostAttribute>()) .AndAlso() .ShouldHave() .InvalidModelState() .AndAlso() .ShouldReturn() .View(v => v .WithModelOfType <EditProjectInputModul>());
public void CreateGetShouldReturnRightModelsAndRightCountriesCount() => MyController <PredictionsController> .Instance() .WithUser() .WithData(data => data .WithEntities(entity => entity.AddRange( new Country { Name = "England" }, new Country { Name = "Finland" }, new Country { Name = "Russia" }))) .Calling(x => x.Create()) .ShouldReturn() .View(viewResult => viewResult .WithModelOfType <CreatePredictionInputViewModel>() .Passing(x => { Assert.Equal(3, x.Countries.Count()); Assert.IsType <List <CountriesDropDownViewModel> >(x.Countries); }));
public void Result_WithValidISIN_ShouldRedirectToDetailsView(string searchTerm) { var shareClass = ShareClassTestData .GenerateShareClasses() .FirstOrDefault(sc => sc.ScIsinCode == searchTerm); var date = DateTime.Today.ToString(GlobalConstants.RequiredWebDateTimeFormat); var routeValues = new { area = EndpointsConstants.ShareClassArea, id = shareClass.ScId, date = date }; MyController <SearchController> .Instance() .WithData(data => data.WithEntities <ApplicationDbContext>(shareClass)) .Calling(c => c.Result(searchTerm)) .ShouldReturn() .RedirectToRoute( EndpointsConstants.RouteDetails + EndpointsConstants.ShareClassArea, routeValues); }
public void AddProduct_WithValidData_ShouldReturnProductShowReceiptViewModel() => MyController <ReceiptController> .Instance() .WithDependencies( this.receiptService, this.productService, this.userManager) .WithUser("testUser") .WithHttpRequest(x => x.WithLocation("/Receipt/Add") .AndAlso() .WithMethod(HttpMethod.Post)) .Calling(x => x.AddProduct(new ReceiptAddProductInputModel() { Id = this.dbContext.Products.FirstOrDefault().Id, Quantity = 4 })) .ShouldHave() .ValidModelState() .AndAlso() .ShouldReturn() .ResultOfType <ActionResult <ProductShowReceiptViewModel> >() .AndAlso() .ShouldPassForThe <ActionResult <ProductShowReceiptViewModel> >(x => x.Value.ProductName == "testProduct");
public void WithEntriesAsIntDictionaryShouldWorkCorrectly() { MyApplication .StartsFrom <DefaultStartup>() .WithServices(services => { services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(); }); MyController <MvcController> .Instance() .WithSession(session => session .WithEntries(new Dictionary <string, int> { ["IntEntry"] = 1 })) .Calling(c => c.FullSessionAction()) .ShouldReturn() .Ok(ok => ok .WithModel(1)); MyApplication.StartsFrom <DefaultStartup>(); }
public void WithoutSetReturnsCorrectDataWhenWholeRangeIsRemoved() { MyApplication .StartsFrom <TestStartup>() .WithServices(services => services.AddDbContext <CustomDbContext>()); var models = new List <CustomModel> { new CustomModel { Id = 1, Name = "Test" } }; MyController <DbContextController> .Instance() .WithData(models) .WithoutData(data => data.WithoutSet <CustomModel>( cm => cm.RemoveRange(models))) .Calling(c => c.GetAll()) .ShouldReturn() .NotFound(); }
public void CreateShouldReturnCreatedResultWhenValidModelState( string country, string state, string city, string description, string postalCode, string phoneNumber) => MyController <AddressesController> .Instance(instance => instance .WithUser()) .Calling(c => c.Create(new AddressesRequestModel { Country = country, State = state, City = city, Description = description, PostalCode = postalCode, PhoneNumber = phoneNumber })) .ShouldHave() .ValidModelState() .AndAlso() .ShouldReturn() .Created();
public void WithIdShouldSetIdCorrectly() { MyApplication .StartsFrom <DefaultStartup>() .WithServices(services => { services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(); }); MyController <MvcController> .Instance() .WithSession(session => session .WithId("TestId") .AndAlso() .WithEntry("HasId", "HasIdValue")) .Calling(c => c.FullSessionAction()) .ShouldReturn() .Ok(ok => ok .WithModel("TestId")); MyApplication.StartsFrom <DefaultStartup>(); }
public void WithControllerContextSetupShouldSetCorrectControllerContextForPocoController() { MyApplication .StartsFrom <DefaultStartup>() .WithServices(services => { services.AddHttpContextAccessor(); }); MyController <FullPocoController> .Instance() .WithControllerContext(controllerContext => { controllerContext.RouteData.Values.Add("testkey", "testvalue"); }) .ShouldPassForThe <FullPocoController>(controller => { Assert.NotNull(controller); Assert.NotNull(controller.CustomControllerContext); Assert.True(controller.CustomControllerContext.RouteData.Values.ContainsKey("testkey")); }); MyApplication.StartsFrom <DefaultStartup>(); }
public void EditShouldHaveAuthorizeAndHttpPostAttributesAndShouldReturnInputViewWhenThemodelStateIsNotValid() => MyController <BlogsController> .Instance() .WithUser(u => u.WithIdentifier(UserId)) .WithData( GetUser(), GetBlog()) .Calling(c => c.Edit(new EditBlogPostInputmodel { Id = 1 })) .ShouldHave() .ActionAttributes(a => a .ContainingAttributeOfType <AuthorizeAttribute>()) .AndAlso() .ShouldHave() .ActionAttributes(a => a. ContainingAttributeOfType <HttpPostAttribute>()) .AndAlso() .ShouldHave() .InvalidModelState() .AndAlso() .ShouldReturn() .View(v => v .WithModelOfType <EditBlogPostInputmodel>());
public void WithEntriesAsIntDictionaryAndWrongKeyShouldReturnBadRequest() { MyApplication .StartsFrom <DefaultStartup>() .WithServices(services => { services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(); }); MyController <MvcController> .Instance() .WithSession(session => session .WithEntries(new Dictionary <string, int> { ["InvalidEntry"] = 1 })) .Calling(c => c.FullSessionAction()) .ShouldReturn() .BadRequest(); MyApplication.StartsFrom <DefaultStartup>(); }
public async Task Should_Upload_Single_File() { //Arrange var fileMock = new Mock <IFormFile>(); //Setup mock file using a memory stream var content = "Hello World from a Fake File"; var fileName = "test.pdf"; var ms = new MemoryStream(); var writer = new StreamWriter(ms); writer.Write(content); writer.Flush(); ms.Position = 0; fileMock.Setup(m => m.OpenReadStream()).Returns(ms); fileMock.Setup(m => m.FileName).Returns(fileName); fileMock.Setup(m => m.Length).Returns(ms.Length); var sut = new MyController(); var file = fileMock.Object; //Act var result = await sut.UploadSingle(file); //Assert Assert.IsInstanceOfType(result, typeof(IActionResult)); }
public void WithCacheOptionsShouldSetCorrectValues() { MyController <MemoryCacheController> .Instance() .WithMemoryCache(memoryCache => memoryCache .WithEntry("FullEntry", "FullEntryValid", new MemoryCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc)), AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1), Priority = CacheItemPriority.High, SlidingExpiration = TimeSpan.FromMinutes(5) })) .Calling(c => c.FullMemoryCacheAction(From.Services <IMemoryCache>())) .ShouldReturn() .Ok(ok => ok .WithModel(new MemoryCacheEntryMock("FullEntry") { Value = "FullEntryValid", AbsoluteExpiration = new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc)), AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1), Priority = CacheItemPriority.High, SlidingExpiration = TimeSpan.FromMinutes(5) })); }
public void WithRequestAsObjectShouldWorkWithSetRequestActionForPocoController() { MyApplication .StartsFrom <DefaultStartup>() .WithServices(services => { services.AddHttpContextAccessor(); }); var httpContext = new HttpContextMock(); httpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues> { ["Test"] = "TestValue" }); MyController <FullPocoController> .Instance() .WithHttpRequest(httpContext.Request) .Calling(c => c.WithRequest()) .ShouldReturn() .Ok(); MyApplication.StartsFrom <DefaultStartup>(); }
protected override void OnChangeMyController(BaseObject oldController) { base.OnChangeMyController(oldController); if (oldController != MyController) { DelayedEventManager.UnregisterEvent(EDelayType.ON_FRAME_END, EEventType.MOVE_ENTITY, new EventHandler(OnPartyMove)); LegacyLogic.Instance.EventManager.UnregisterEvent(EEventType.NPC_HIRELING_UPDATED, new EventHandler(OnNPCHirelingUpdated)); LegacyLogic.Instance.EventManager.UnregisterEvent(EEventType.TOKEN_ADDED, new EventHandler(CheckVisibility)); LegacyLogic.Instance.EventManager.UnregisterEvent(EEventType.PARTY_BUFF_ADDED, new EventHandler(CheckVisibility)); LegacyLogic.Instance.EventManager.UnregisterEvent(EEventType.PARTY_BUFF_REMOVED, new EventHandler(CheckVisibility)); } if (MyController != null && !(MyController is InteractiveObject)) { Debug.LogError("DiscoverHighlightViewBase: OnChangeMyController: works only for InteractiveObjects! Was given '" + MyController.GetType().FullName + "'"); return; } if (MyController != null) { DelayedEventManager.RegisterEvent(EDelayType.ON_FRAME_END, EEventType.MOVE_ENTITY, new EventHandler(OnPartyMove)); LegacyLogic.Instance.EventManager.RegisterEvent(EEventType.NPC_HIRELING_UPDATED, new EventHandler(OnNPCHirelingUpdated)); LegacyLogic.Instance.EventManager.RegisterEvent(EEventType.TOKEN_ADDED, new EventHandler(CheckVisibility)); LegacyLogic.Instance.EventManager.RegisterEvent(EEventType.PARTY_BUFF_ADDED, new EventHandler(CheckVisibility)); LegacyLogic.Instance.EventManager.RegisterEvent(EEventType.PARTY_BUFF_REMOVED, new EventHandler(CheckVisibility)); } }
public void AttributesShouldNotThrowExceptionWithControllerContainingNumberOfAttributes() { MyController <MvcController> .ShouldHave() .Attributes(withTotalNumberOf: 4); }
public void ByNameShouldHaveAuthorizedUsersOnlyRestriction() => MyController <ListsController> .Calling(c => c.ByName("lll")) .ShouldHave() .ActionAttributes(attr => attr .RestrictingForAuthorizedRequests());
public void IHttpContextAccessorShouldWorkCorrectlyAsynchronously() { MyApplication .StartsFrom <DefaultStartup>() .WithServices(services => { services.AddHttpContextAccessor(); }); Task .Run(async() => { HttpContext firstContextAsync = null; HttpContext secondContextAsync = null; HttpContext thirdContextAsync = null; HttpContext fourthContextAsync = null; HttpContext fifthContextAsync = null; var tasks = new List <Task> { Task.Run(() => { MyController <HttpContextController> .Instance() .ShouldPassForThe <HttpContextController>(controller => { firstContextAsync = controller.Context; }); }), Task.Run(() => { MyController <HttpContextController> .Instance() .ShouldPassForThe <HttpContextController>(controller => { secondContextAsync = controller.Context; }); }), Task.Run(() => { MyController <HttpContextController> .Instance() .ShouldPassForThe <HttpContextController>(controller => { thirdContextAsync = controller.Context; }); }), Task.Run(() => { MyController <HttpContextController> .Instance() .ShouldPassForThe <HttpContextController>(controller => { fourthContextAsync = controller.Context; }); }), Task.Run(() => { MyController <HttpContextController> .Instance() .ShouldPassForThe <HttpContextController>(controller => { fifthContextAsync = controller.Context; }); }) }; await Task.WhenAll(tasks); Assert.NotNull(firstContextAsync); Assert.NotNull(secondContextAsync); Assert.NotNull(thirdContextAsync); Assert.NotNull(fourthContextAsync); Assert.NotNull(fifthContextAsync); Assert.IsAssignableFrom <HttpContextMock>(firstContextAsync); Assert.IsAssignableFrom <HttpContextMock>(secondContextAsync); Assert.IsAssignableFrom <HttpContextMock>(thirdContextAsync); Assert.IsAssignableFrom <HttpContextMock>(fourthContextAsync); Assert.IsAssignableFrom <HttpContextMock>(fifthContextAsync); Assert.NotSame(firstContextAsync, secondContextAsync); Assert.NotSame(firstContextAsync, thirdContextAsync); Assert.NotSame(secondContextAsync, thirdContextAsync); Assert.NotSame(thirdContextAsync, fourthContextAsync); Assert.NotSame(fourthContextAsync, fifthContextAsync); Assert.NotSame(thirdContextAsync, fifthContextAsync); }) .ConfigureAwait(false) .GetAwaiter() .GetResult(); MyApplication.StartsFrom <DefaultStartup>(); }
public void Should_resolve_parameters_for_action_invoker() { var myController = new MyController(); executor.ExecuteActionWithFilters(controller => controller.Index(), myController, () => new MyActionInvoker(17)); Assert.That(myController.ActionInvoker, Has.Property("DummyInt").EqualTo(17)); }
public void Should_allow_action_invoker_expressions_that_do_not_instantiate() { var myController = new MyController(); executor.ExecuteActionWithFilters(controller => controller.Index(), myController, () => InvokerFactory.Invoker); Assert.That(myController.ActionInvoker, Is.InstanceOf<ControllerActionInvoker>()); }
public void SetUp() { _controller = new MyController(); _data = new IsopServerFromBuild( ()=> new Build().Recognize(_controller)); }
public void DefaultControllerFactory_DelegatesDisposalToControllerActivator() { // Arrange var activatorMock = new Mock<IControllerActivator>(); activatorMock.Setup(s => s.Release(It.IsAny<ControllerContext>(), It.IsAny<object>())); var factory = CreateControllerFactory(activatorMock.Object); var controller = new MyController(); // Act + Assert factory.ReleaseController(new ControllerContext(), controller); activatorMock.Verify(); }
private void btnNoLogin_Click(object sender, System.EventArgs e) { MyController.DoNotLogMeIn(); }
public void DetailsShouldHaveRestrictionsForAuthorizedUsers() => MyController <CategoriesController> .Calling(c => c.Details(1, "")) .ShouldHave() .ActionAttributes(attr => attr .RestrictingForAuthorizedRequests());
public void Release_DisposesController_IfDisposable() { // Arrange var controller = new MyController(); var activator = new DefaultControllerActivator(Mock.Of<ITypeActivatorCache>()); // Act activator.Release(new ControllerContext(), controller); // Assert Assert.Equal(true, controller.Disposed); }
public void ControllerShouldHaveAuthorizeAttributeForAdminsOnly() => MyController <AppointmentsController> .ShouldHave() .Attributes(attributes => attributes .SpecifyingArea(AdminArea) .RestrictingForAuthorizedRequests(AdminRole));
private void LogoutButtonClick(object sender, RoutedEventArgs e) { MyController.Logout(); Application.Current.Shutdown(); }
public void HomeControllerShouldReturnView() => MyController <HomeController> .Instance() .Calling(c => c.Index()) .ShouldReturn() .View();
private void TestGet() { MyController controller = new MyController(); IHttpResponse response; IHttpSession session = DefaultSession; string text = Get(controller, "/my/hello/1?hello=world", out response, session); Assert.Equal("world|1", text); }
public override void Execute() { //La idea es ir a la direccion contraria del tagged actor MyController.GoToLocation(transform.InverseTransformPoint(MyController.NearestTagged.transform.position)); }
private void TestPost() { MyController controller = new MyController(); IHttpResponse response; IHttpSession session = DefaultSession; HttpForm form = new HttpForm(); form.Add("user[firstName]", "jonas"); string text = Post(controller, "/my/hello/id", form, out response, session); Assert.Equal("jonas", text); }