示例#1
0
        public void ListadoExpedienteConPedimentoInexistenteRegresaError()
        {
            //Arrange
            //ClaimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity().)

            Moq.Mock <IIdentityExtensions> mockI = new Moq.Mock <IIdentityExtensions>();
            mockI.Setup(s => s.GetClientId(It.IsAny <IIdentity>())).Returns("590");
            mockI.Setup(s => s.GetNombreCliente(It.IsAny <IIdentity>())).Returns("DANFOSS INDUSTRIES S. DE R. L.");

            IdentityExtensions.Implementation = mockI.Object;

            Moq.Mock <ClaimsPrincipal> mockP = new Moq.Mock <ClaimsPrincipal>();
            mockP.SetupGet(p => p.Identity.Name).Returns("*****@*****.**");
            mockP.Setup(p => p.IsInRole("Administrador")).Returns(false);
            mockP.Setup(p => p.FindFirst("ClientId")).Returns(new Claim("ClientId", "590"));
            mockP.As <IPrincipal>();
            IPrincipal unmockedIPrincipal = mockP.Object;

            //((ClaimsIdentity)unmockedIPrincipal.Identity).AddClaim(new Claim("ClientId", "590"));

            Moq.Mock <ControllerContext> mockContext = new Moq.Mock <ControllerContext>();
            mockContext.SetupGet(p => p.HttpContext.User).Returns(unmockedIPrincipal);
            mockContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

            var controller = new InternetReports.Areas.Operacion.Controllers.DescargaExpedientesController();

            controller.ControllerContext = mockContext.Object;
            controller._catalogos        = new InternetReports.Models.FakeARCHIVOS_ALT();
            var pedimento = new InternetReports.Models.PedimentosSaaiSirView()
            {
                Referencia = "1900024-00",
                Pedimento  = "9000751",
                Aduana     = "81",
                Seccion    = "0",
                IdClienteC = 590,
                IdClienteP = 590,
                FechaPago  = new DateTime(2019, 1, 10)
            };

            controller._catalogos.PedimentosSaaiSirViews.Add(pedimento);
            controller._catalogos.SaveChanges();

            BusquedaExpedienteViewModel busquedaViewModel = new BusquedaExpedienteViewModel()
            {
                Pedimento = "9000754",
                Aduana    = "810",
                Año       = "2019"
            };

            //Act
            ViewResult result = controller.ListadoExpediente(busquedaViewModel).Result as ViewResult;

            //Assert
            Assert.AreEqual("Index", result.ViewName);
            Assert.IsTrue(result.ViewData.ModelState.ContainsKey("PedimentoNoEncontrado"));
            Assert.IsNotNull(result.ViewData.ModelState["PedimentoNoEncontrado"].Errors);
            Assert.IsNotNull(result.ViewData.ModelState["PedimentoNoEncontrado"].Errors.Contains(new ModelError("No se encontró el pedimento o la referencia requerida")));
        }
		public static Mock<IPublishedContent> Content(string name, IEnumerable<IPublishedContent> children)
		{
			var mockedItem = new Moq.Mock<IPublishedContent>();
			mockedItem.SetupGet(m => m.Id).Returns(1);
			mockedItem.SetupGet(m => m.Name).Returns(name);
			mockedItem.SetupGet(m => m.Children).Returns(children);

			return mockedItem;
		}
示例#3
0
        public void InsertUpdateUIConfigs()
        {
            GeneralSettings genS = new GeneralSettings();

            genS.CloudStorageConnectionString = _fixture.Configuratuion.GetSection("General").GetSection("CloudStorageConnectionString").Value.ToString();

            //Need to Mock the injected services and setup any properties on these that the test requires
            var errorSettingsMoq = new Moq.Mock <IOptions <ErrorSettings> >();

            var generalSettingsMoq = new Moq.Mock <IOptions <GeneralSettings> >();

            generalSettingsMoq.SetupGet(p => p.Value.CloudStorageConnectionString).Returns(genS.CloudStorageConnectionString);

            var environmentMoq = new Moq.Mock <IHostingEnvironment>();

            environmentMoq.SetupGet(p => p.WebRootPath).Returns(@"C:\Repos\mcfork\tree\master\cloud\\src\solution\Microsoft.Legal.MatterCenter.Web\wwwroot");

            var matterCenterServiceFunctionsMoq = new Moq.Mock <IMatterCenterServiceFunctions>();

            var uiConfigsMoq = new Moq.Mock <IOptions <UIConfigSettings> >();

            uiConfigsMoq.SetupGet(t => t.Value.MatterCenterConfiguration).Returns("MatterCenterConfiguration");
            uiConfigsMoq.SetupGet(p => p.Value.Partitionkey).Returns("MatterCenterConfig");
            uiConfigsMoq.SetupGet(c => c.Value.ConfigGroup).Returns("ConfigGroup");
            uiConfigsMoq.SetupGet(k => k.Value.Key).Returns("Key");
            uiConfigsMoq.SetupGet(v => v.Value.Value).Returns("Value");

            var logTableMoq = new Moq.Mock <IOptions <LogTables> >();

            ConfigRepository configRepository = new ConfigRepository(null, generalSettingsMoq.Object, uiConfigsMoq.Object);

            generalSettingsMoq.SetupGet(g => g.Value).Returns(genS);
            errorSettingsMoq.SetupAllProperties();

            ConfigController controller = new ConfigController(errorSettingsMoq.Object, generalSettingsMoq.Object, uiConfigsMoq.Object, logTableMoq.Object, matterCenterServiceFunctionsMoq.Object, configRepository, environmentMoq.Object);


            var configsStr = (@"{""Home"": {
    ""ContextualHelpHeader"": ""Matter Center For Outlook"",
    ""ContextualHelpBottomText"": ""Questions? Contact "",
    ""HelpRequesURL"": ""https://msmatter.sharepoint.com/sites/catalog"",
    ""MatterCenterSupportLinkText"": ""Matter Center Aisling Support"",
    ""MatterCenterSupportLink"": ""mailto:[email protected]"",
    ""Change"": ""mailto:[email protected]"",
  },
  ""MatterUsers"": {
    ""SearchUsersURL"": ""https://msmatter.sharepoint.com/sites/client"",
    ""StampedPropertiesURL"": ""https://msmatter.sharepoint.com/sites/microsoft"",
    ""Add"": ""test"",
  }}");



            var result = controller.InsertUpdate(configsStr);

            Assert.True(result.Status > 0);
        }
示例#4
0
        public void Setup()
        {
            var httpContextBaseMock = new Moq.Mock <HttpContextBase>();

            var httpRequestBase = new Moq.Mock <HttpRequestBase>();

            httpRequestBase.SetupGet(r => r.ApplicationPath).Returns(@"\");
            httpContextBaseMock.SetupGet(c => c.Items).Returns(new Dictionary <string, object>());
            httpRequestBase.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());
            httpRequestBase.Object.Cookies.Add(new HttpCookie(GlimpseConstants.CookieModeKey, "On"));

            httpContextBaseMock.SetupGet(c => c.Request).Returns(httpRequestBase.Object);
            httpContext = httpContextBaseMock.Object;
        }
示例#5
0
        public async Task ApiPersonDataSourceTests_BadData()
        {
            // Arrange
            var logger        = new Moq.Mock <ILogger <ApiPersonDataSource> >();
            var configuration = new Moq.Mock <IConfiguration>();

            configuration.SetupGet(c => c["PersonApi"]).Returns(@"https://google.com/").Verifiable();
            var memoryCache = new FakeMemoryCache();

            var httpClientFactory = ArrangeHttpClient(
                new HttpClientResponse()
            {
                UrlSuffix    = "https://google.com/",
                ResponseFunc = (r) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(FileHelper.GetAsString(@".\TestData\example_data_bad.json"))
                })
            }
                );

            var sut = new ApiPersonDataSource(logger.Object, configuration.Object, memoryCache, httpClientFactory);

            // Act
            Func <Task> act = async() => await sut.Get();

            // Assert
            act.Should().Throw <JsonReaderException>();
        }
示例#6
0
        public void TestBindIds()
        {
            var binder = new TypeDataBinder(new Mock <IXLogger>().Object);
            IEnumerable <IBinding> bindings;

            IPage page = null;

            IRawDependencyGroup dependencies;

            binder.Bind <DataModelMock1>(
                a =>
            {
                page = new Moq.Mock <IPage>().Object;
                return(page);
            },
                (Type t, IAttributeSet a, IGroup p, IMetadata md, out int r) =>
            {
                r            = 1;
                var ctrlMock = new Moq.Mock <IControl>();
                ctrlMock.SetupGet(c => c.Id).Returns(() => a.Id);
                return(ctrlMock.Object);
            }, x => null, out bindings, out dependencies);

            Assert.AreEqual(0, bindings.ElementAt(0).Control.Id);
            Assert.AreEqual(1, bindings.ElementAt(1).Control.Id);
            Assert.AreEqual(2, bindings.ElementAt(2).Control.Id);
        }
        public void TestLongRunningProcess()
        {
            var reducer = new ReducerComposer <AppState>();

            var anyActionLogicMock = new Moq.Mock <ILogic <AppState, ListenInternetConnection> >();

            anyActionLogicMock.SetupGet(x => x.IsLongRunning).Returns(true);
            anyActionLogicMock.Setup(x => x.PreProcess(It.IsAny <IStore <AppState> >(), It.IsAny <ListenInternetConnection>())).ReturnsAsync(new PreProcessResult(true, new ListenInternetConnection()));
            anyActionLogicMock.Setup(x => x.Process(It.IsAny <Func <AppState> >(), It.IsAny <ListenInternetConnection>(), It.IsAny <IMultiDispatcher>())).Callback(() =>
            {
                // Basically hangs if IsLongRunning is set to false.
                Task.Delay(TimeSpan.MaxValue).Wait();
            });

            var nextActionLogicMock = new Moq.Mock <ILogic <AppState, AnyAction> >();

            nextActionLogicMock.Setup(x => x.PreProcess(It.IsAny <IStore <AppState> >(), It.IsAny <AnyAction>())).ReturnsAsync(new PreProcessResult(true, new ListenInternetConnection()));
            IStore <AppState> store = new Store <AppState>(reducer, AppState.InitialState).ConfigureLogic(config =>
            {
                config.AddLogics(anyActionLogicMock.Object);
                config.AddLogics(nextActionLogicMock.Object);
            });

            store.Dispatch(new ListenInternetConnection());
            nextActionLogicMock.Verify(x => x.PreProcess(It.IsAny <IStore <AppState> >(), It.IsAny <AnyAction>()), Times.Once());
            anyActionLogicMock.Verify(x => x.Process(It.IsAny <Func <AppState> >(), It.IsAny <ListenInternetConnection>(), It.IsAny <IMultiDispatcher>()), Times.Once());
        }
示例#8
0
        public async Task LoginFailedTest()
        {
            Mock <UserGrain> user = new Moq.Mock <UserGrain>(Moq.MockBehavior.Loose);

            user.SetupGet(u => u.Email).Returns("*****@*****.**");
            Assert.IsFalse(await user.Object.Login("2"));
        }
        public void ReadsCorrectly()
        {
            // arrange
            var converter = new EnumConverter();
            var reader1   = new Moq.Mock <JsonReader>();

            reader1.SetupGet(x => x.Value).Returns(null);
            var reader2 = new Moq.Mock <JsonReader>();

            reader2.SetupGet(x => x.Value).Returns("0");
            var reader3 = new Moq.Mock <JsonReader>();

            reader3.SetupGet(x => x.Value).Returns("1");

            // act
            var object1 = converter.ReadJson(reader1.Object, typeof(System.ConsoleColor), null, null);
            var object2 = converter.ReadJson(reader1.Object, typeof(System.ConsoleColor?), null, null);
            var object3 = converter.ReadJson(reader2.Object, typeof(System.ConsoleColor), null, null);
            var object4 = converter.ReadJson(reader3.Object, typeof(System.ConsoleColor), null, null);

            // assert
            Assert.IsNull(object1);
            Assert.IsNull(object2);
            Assert.AreEqual(System.ConsoleColor.Black, (System.ConsoleColor)object3);
            Assert.AreEqual(System.ConsoleColor.DarkBlue, (System.ConsoleColor)object4);
        }
示例#10
0
        public void Test_MVCController_Can_Create_User_With_Valid_Inputs()
        {
            try
            {
                var controllerContext = new Mock <ControllerContext>();
                var principal         = new Moq.Mock <IPrincipal>();
                principal.SetupGet(x => x.Identity.Name).Returns("uname");
                controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);

                var userStub = new Mock <SetPropertiesViewModel>().SetupAllProperties();
                userStub.Setup(x => x.FirstName).Returns("Adam");
                userStub.Setup(x => x.LastName).Returns("Adam");
                userStub.Setup(x => x.AddressLine).Returns("Adaminsæøa");
                userStub.Setup(x => x.CityName).Returns("Ålborg");
                userStub.Setup(x => x.Postcode).Returns("9000");
                userStub.Setup(x => x.Region).Returns(Region.Nordjylland);
                userStub.Setup(x => x.Gender).Returns(Gender.Male);

                var serviceMock = new Mock <IUserService>();

                serviceMock.Setup(x => x.CreateUser(It.IsAny <User>(), It.IsAny <String>())).Returns(true);

                var subject = new AccountController(serviceMock.Object);
                subject.ControllerContext = controllerContext.Object;
                var result = subject.SetUserProperties(userStub.Object);

                Assert.IsInstanceOfType(result, typeof(ActionResult));
            }
            catch
            {
                Assert.Fail();
            }
        }
        public void ReadsCorrectly()
        {
            // arrange
            var converter = new BoolConverter();
            var reader1   = new Moq.Mock <JsonReader>();

            reader1.SetupGet(x => x.Value).Returns(null);
            var reader2 = new Moq.Mock <JsonReader>();

            reader2.SetupGet(x => x.Value).Returns("0");
            var reader3 = new Moq.Mock <JsonReader>();

            reader3.SetupGet(x => x.Value).Returns("1");

            // act
            var object1 = converter.ReadJson(reader1.Object, typeof(bool), null, null);
            var object2 = converter.ReadJson(reader1.Object, typeof(bool?), null, null);
            var object3 = converter.ReadJson(reader2.Object, typeof(bool), null, null);
            var object4 = converter.ReadJson(reader3.Object, typeof(bool), null, null);

            // assert
            Assert.IsAssignableFrom <bool>(object1);
            Assert.IsFalse((bool)object1);
            Assert.IsNull(object2);
            Assert.IsFalse((bool)object3);
            Assert.IsTrue((bool)object4);
        }
示例#12
0
        public void ViewDetails_UpdateOffer_View_Tests_If_Rederict_to_Action()
        {
            try
            {
                ViewDetailsModel detail = new ViewDetailsModel();
                detail.Id          = 3;
                detail.Title       = "234567";
                detail.RatePerHour = 122;
                detail.Description = "2345678765433456";

                var controllerContext = new Mock <ControllerContext>();
                var principal         = new Moq.Mock <IPrincipal>();
                principal.SetupGet(x => x.Identity.Name).Returns("uname");
                //principal.SetupGet(x => x.Identity.GetUserId()).Returns("uname");
                controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);

                var serviceMock = new Mock <MyWeb.OfferReference.IOfferService>();
                serviceMock.Setup(x => x.UpdateServiceOfferAsync(It.IsAny <Offer>())).ReturnsAsync(true);

                var ctr = new ServiceOfferController(serviceMock.Object);
                ctr.ControllerContext = controllerContext.Object;
                var result = ctr.ViewDetails(detail).Result;//Task<actionRsult>>
                RedirectToRouteResult routeResult = result as RedirectToRouteResult;
                Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));

                Assert.AreEqual(routeResult.RouteValues["action"], "UserProfile");
            }
            catch
            {
                Assert.Fail();
            }
        }
        public void Setup()
        {
            _mockAdmin = new Mock <IAdminService>();
            _mockAdmin.Setup(x => x.GetUsers()).Returns(new List <User>());
            _mockRentMapper = new Mock <IRentMapperDM>();
            _mockRentMapper.Setup(x => x.ToCarDM.Map <CarDTO, CarDM>(null)).Returns(new CarDM());
            _mockRentMapper.Setup(x => x.ToCarDM.Map <CarDTO, CarDM>(new CarDTO())).Returns(new CarDM());
            _mockRentMapper.Setup(x => x.ToCarDM.Map <IEnumerable <CarDTO>, List <CarDM> >(new List <CarDTO>()))
            .Returns(new List <CarDM>());
            _mockRentMapper.Setup(x => x.ToImageDTO.Map <List <ImageDM>, IEnumerable <ImageDTO> >(new List <ImageDM>()))
            .Returns(null as List <ImageDTO>);
            _mockIdentityMapper = new Mock <IIdentityMapperDM>();
            _mockIdentityMapper.Setup(x => x.ToUserDM.Map <IEnumerable <User>, List <UserDM> >(new List <User>()))
            .Returns(new List <UserDM>());
            _mockRent = new Mock <IRentService>();
            _mockRent.Setup(x => x.GetCar(1)).Returns(new CarDTO());
            _mockRent.Setup(x => x.GetCars()).Returns(new List <CarDTO>());
            _mockLog = new Mock <ILogWriter>();

            var controllerContext = new Mock <ControllerContext>();
            var principal         = new Moq.Mock <IPrincipal>();

            principal.Setup(p => p.IsInRole("Administrator")).Returns(true);
            principal.SetupGet(x => x.Identity.Name).Returns("name");
            controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);

            _controller = new AdminController(_mockAdmin.Object, _mockIdentityMapper.Object, _mockRentMapper.Object,
                                              _mockRent.Object, _mockLog.Object)
            {
                ControllerContext = controllerContext.Object
            };
        }
示例#14
0
        public void Add_New_Topic_Route_Test()
        {
            Mock <ITopicRepository> topicRepo = new Mock <ITopicRepository>();
            Mock <IIntermediateCategoryRepository> interRepo = new Mock <IIntermediateCategoryRepository>();


            var controllerContext = new Mock <ControllerContext>();
            var principal         = new Moq.Mock <IPrincipal>();

            principal.Setup(p => p.IsInRole("Administrator")).Returns(true);
            principal.SetupGet(x => x.Identity.Name).Returns("koral2323");
            principal.Setup(c => c.Identity.IsAuthenticated).Returns(true);

            controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);



            TopicController controller = new TopicController(topicRepo.Object, interRepo.Object);

            controller.ControllerContext = controllerContext.Object;

            Topic topic = new Topic();

            topic.IntermediateCategoryId = 3;

            RedirectToRouteResult result = controller.Add_New_Topic(topic) as RedirectToRouteResult;

            Assert.AreEqual(result.RouteValues["action"], "Show_Topics");
            Assert.AreEqual(result.RouteValues["controller"], "Topic");
            Assert.AreEqual(result.RouteValues["id"], 3);
        }
        public void Setup()
        {
            _mockClient     = new Mock <IClientService>();
            _mockRentMapper = new Mock <IRentMapperDM>();
            _mockRentMapper.Setup(x => x.ToOrderDM.Map <IEnumerable <OrderDTO>, List <OrderDM> >(new List <OrderDTO>()))
            .Returns(new List <OrderDM>());
            _mockRentMapper.Setup(x => x.ToPaymentDM.Map <IEnumerable <PaymentDTO>, List <PaymentDM> >(new List <PaymentDTO>()))
            .Returns(new List <PaymentDM>());
            _mockRentMapper.Setup(x => x.ToCarDM.Map <CarDTO, CarDM>(null)).Returns(new CarDM());
            _mockIdentityMapper = new Mock <IIdentityMapperDM>();
            _mockRent           = new Mock <IRentService>();
            _mockLog            = new Mock <ILogWriter>();

            var controllerContext = new Mock <ControllerContext>();
            var principal         = new Moq.Mock <IPrincipal>();

            principal.Setup(p => p.IsInRole("Administrator")).Returns(true);
            principal.SetupGet(x => x.Identity.Name).Returns("name");
            controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);

            _controller = new ClientController(_mockClient.Object, _mockIdentityMapper.Object,
                                               _mockRentMapper.Object, _mockRent.Object, _mockLog.Object)
            {
                ControllerContext = controllerContext.Object
            };
        }
示例#16
0
        public void ParseTasksDeleteTask()
        {
            var mockTaskCreator = new Mock <ITaskCreator>();

            // mock a task which Id is 2
            var mockUpdateTask = new Moq.Mock <ITask>();

            mockUpdateTask.SetupGet(x => x.Id).Returns(2);
            mockTaskCreator.Setup(ct => ct.Creator(It.IsAny <string>()))
            .Returns(mockUpdateTask.Object);
            var target = new TaskManager(
                mockTaskCreator.Object,
                this.mockNetworkClient.Object,
                this.mockExceptionPolicy.Object, null);

            // this set is not complete, it ignores the content for TaskCreator. execute
            // create first
            var taskxml =
                "<Tasks><Task><Id>2></Id>"
                + "<Action>Create</Action></Task></Tasks>";

            target.ParseTasks(taskxml);
            Assert.AreEqual(target.Tasks.Count, 1);

            // this is for test delete action
            taskxml = "<Tasks><Task><Id>2</Id>"
                      + "<Action>Delete</Action></Task></Tasks>";
            target.ParseTasks(taskxml);
            mockTaskCreator.Verify(
                m => m.Creator(It.IsAny <string>()), Times.Exactly(2));
            Assert.AreEqual(target.Tasks.Count, 0);
        }
示例#17
0
        public void Setup()
        {
            _mockManager = new Mock <IManagerService>();
            _mockManager.Setup(x => x.GetForReturns()).Returns(new List <OrderDTO>());
            _mockRentMapper = new Mock <IRentMapperDM>();
            _mockManager.Setup(x => x.GetForConfirms()).Returns(new List <OrderDTO>());
            _mockRentMapper.Setup(x => x.ToOrderDM.Map <IEnumerable <OrderDTO>, List <OrderDM> >(new List <OrderDTO>()))
            .Returns(new List <OrderDM>());
            _mockIdentityMapper = new Mock <IIdentityMapperDM>();
            _mockIdentityMapper.Setup(x => x.ToProfileDM.Map <ProfileDTO, ProfileDM>(null)).Returns(new ProfileDM());
            _mockLog = new Mock <ILogWriter>();

            var controllerContext = new Mock <ControllerContext>();
            var principal         = new Moq.Mock <IPrincipal>();

            principal.Setup(p => p.IsInRole("Administrator")).Returns(true);
            principal.SetupGet(x => x.Identity.Name).Returns("name");
            controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);

            _controller = new ManagerController(_mockManager.Object,
                                                _mockRentMapper.Object, _mockLog.Object, _mockIdentityMapper.Object)
            {
                ControllerContext = controllerContext.Object
            };
        }
示例#18
0
文件: Data.cs 项目: jrivam/demo
        GetDatabaseMock()
        {
            //var mockMapper = new Moq.Mock<IMapperTable<domain.Model.Empresa, data.Model.Empresa>>();

            //mockMapper.Setup(x => x.Read(It.IsAny<data.Model.Empresa>(), It.IsAny<IDataReader>(), It.IsAny<IList<string>>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
            //    .Returns((data.Model.Empresa data, IDataReader reader, IList<string> prefixname, string aliasseparator, int maxdepth, int depth) =>
            //    {
            //        data["Id"].Value = data["Id"].DbValue = data.Id;
            //        data["RazonSocial"].Value = data["RazonSocial"].DbValue = "razon social";
            //        data["Activo"].Value = data["Activo"].DbValue = true;

            //        return data;
            //    });

            var mockConnection = new Moq.Mock <IDbConnection>();

            var mockCommand = new Moq.Mock <IDbCommand>();

            mockCommand.SetupGet <IDbConnection>(x => x.Connection)
            .Returns(mockConnection.Object);

            var mockSyntaxSign = new Moq.Mock <ISqlSyntaxSign>();

            mockSyntaxSign.SetupGet <string>(x => x.AliasSeparatorColumn)
            .Returns(".");

            var mockObjectCreator = new Moq.Mock <IDbObjectCreator>();

            var mockCreator = new Moq.Mock <ISqlCreator>();

            mockCreator.Setup(x => x.GetCommand(It.IsAny <string>(), It.IsAny <CommandType>(), It.IsAny <IList <SqlParameter> >()))
            .Returns(mockCommand.Object);

            return(mockCommand, mockSyntaxSign, mockCreator);
        }
示例#19
0
        public void ChangeMail_check_if_redirect_to_correct_action()
        {
            try
            {
                var controllerContext = new Mock <ControllerContext>();
                var principal         = new Moq.Mock <IPrincipal>();
                principal.SetupGet(x => x.Identity.Name).Returns("uname");
                controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);

                ChangeEmailViewModel mail = new ChangeEmailViewModel();
                mail.NewEmail             = "*****@*****.**";
                mail.OldEmail             = "*****@*****.**";
                mail.UserProfileViewModel = new UserProfileViewModel();
                mail.Id = 2;
                var serviceMock      = new Mock <IUserService>();
                var serviceOfferMock = new Mock <IOfferService>();
                var serviceOrderMock = new Mock <IOrderService>();
                serviceMock.Setup(s => s.EditUserEmailAsync(It.IsAny <User>())).ReturnsAsync(true);
                var controller = new UserController(serviceMock.Object, serviceOfferMock.Object, serviceOrderMock.Object);
                controller.ControllerContext = controllerContext.Object;

                var task   = controller.ChangeEmail(mail);//Task<actionRsult>>
                var result = task.Result;
                Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
                RedirectToRouteResult routeResult = result as RedirectToRouteResult;
                Assert.AreEqual(routeResult.RouteValues["action"], "UserProfile");
                Assert.AreEqual(routeResult.RouteValues["controller"], "User");
            }

            catch
            {
                Assert.Fail();
            }
        }
示例#20
0
        public void Delete_View_Tests_If_Rederict_to_Action()
        {
            try
            {
                var controllerContext = new Mock <ControllerContext>();
                var principal         = new Moq.Mock <IPrincipal>();
                principal.SetupGet(x => x.Identity.Name).Returns("uname");
                //principal.SetupGet(x => x.Identity.GetUserId()).Returns("uname");
                controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
                var serviceMock = new Mock <MyWeb.OfferReference.IOfferService>();
                serviceMock.Setup(x => x.DeleteServiceOfferAsync(It.IsAny <int>())).ReturnsAsync(true);

                var ctr = new ServiceOfferController(serviceMock.Object);
                ctr.ControllerContext = controllerContext.Object;
                var task   = ctr.Delete(1);//Task<actionRsult>>
                var result = task.Result;
                Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
                RedirectToRouteResult routeResult = result as RedirectToRouteResult;
                Assert.AreEqual(routeResult.RouteValues["action"], "UserProfile");
            }
            catch
            {
                Assert.Fail();
            }
        }
示例#21
0
        public void Test_AddDescription_checking()
        {
            try
            {
                var controllerContext = new Mock <ControllerContext>();
                var principal         = new Moq.Mock <IPrincipal>();
                principal.SetupGet(x => x.Identity.Name).Returns("uname");
                //principal.SetupGet(x => x.Identity.GetUserId()).Returns("uname");
                controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
                var dmock = new Mock <ChangeDescriptionViewModel>();
                dmock.SetupAllProperties();
                var serviceMock      = new Mock <IUserService>();
                var serviceOfferMock = new Mock <IOfferService>();
                var serviceOrderMock = new Mock <IOrderService>();
                serviceMock.Setup(s => s.AddDescriptionAsync(It.IsAny <User>())).ReturnsAsync(true);
                var controller = new UserController(serviceMock.Object, serviceOfferMock.Object, serviceOrderMock.Object);
                controller.ControllerContext = controllerContext.Object;

                var task   = controller.AddDescription(dmock.Object);//Task<actionRsult>>
                var result = task.Result;
                Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
                RedirectToRouteResult routeResult = result as RedirectToRouteResult;
                Assert.AreEqual(routeResult.RouteValues["action"], "UserProfile");
                Assert.AreEqual(routeResult.RouteValues["controller"], "User");
            }

            catch
            {
                Assert.Fail();
            }
        }
示例#22
0
        public async Task RegisterTest()
        {
            Mock <UserGrain> user = new Moq.Mock <UserGrain>(Moq.MockBehavior.Loose);
            Guid             g    = Guid.NewGuid();

            user.SetupGet(u => u.Email).Returns($"avi.kessler+{g.ToString("N")}@gmail.com");
            Assert.IsTrue(await user.Object.Register(g.ToString("N")));
        }
示例#23
0
        public void GetAllUIConfigsForSPO()
        {
            GeneralSettings genS = new GeneralSettings();

            genS.CloudStorageConnectionString = _fixture.Configuratuion.GetSection("General").GetSection("CloudStorageConnectionString").Value.ToString();

            //Need to Mock the injected services and setup any properties on these that the test requires
            var errorSettingsMoq = new Moq.Mock <IOptions <ErrorSettings> >();

            var generalSettingsMoq = new Moq.Mock <IOptions <GeneralSettings> >();

            generalSettingsMoq.SetupGet(p => p.Value.CloudStorageConnectionString).Returns(genS.CloudStorageConnectionString);
            generalSettingsMoq.SetupGet(p => p.Value.AdminUserName).Returns(_fixture.Configuratuion.GetSection("General").GetSection("AdminUserName").Value.ToString());
            generalSettingsMoq.SetupGet(p => p.Value.AdminPassword).Returns(_fixture.Configuratuion.GetSection("General").GetSection("AdminPassword").Value.ToString());
            generalSettingsMoq.SetupGet(p => p.Value.CentralRepositoryUrl).Returns("https://msmatter.sharepoint.com/sites/catalog");

            var environmentMoq = new Moq.Mock <IHostingEnvironment>();

            environmentMoq.SetupGet(p => p.WebRootPath).Returns(@"C:\projects\mc2\tree\master\cloud\src\solution\Microsoft.Legal.MatterCenter.Web\wwwroot");

            var matterCenterServiceFunctionsMoq = new Moq.Mock <IMatterCenterServiceFunctions>();

            var uiConfigsMoq = new Moq.Mock <IOptions <UIConfigSettings> >();

            uiConfigsMoq.SetupGet(t => t.Value.MatterCenterConfiguration).Returns("MatterCenterConfiguration");
            uiConfigsMoq.SetupGet(p => p.Value.Partitionkey).Returns("MatterCenterConfig");
            uiConfigsMoq.SetupGet(c => c.Value.ConfigGroup).Returns("ConfigGroup");
            uiConfigsMoq.SetupGet(k => k.Value.Key).Returns("Key");
            uiConfigsMoq.SetupGet(v => v.Value.Value).Returns("Value");


            var logTableMoq = new Moq.Mock <IOptions <LogTables> >();

            ConfigRepository configRepository = new ConfigRepository(null, generalSettingsMoq.Object, uiConfigsMoq.Object);

            generalSettingsMoq.SetupGet(g => g.Value).Returns(genS);
            errorSettingsMoq.SetupAllProperties();


            ConfigController controller = new ConfigController(errorSettingsMoq.Object, generalSettingsMoq.Object, uiConfigsMoq.Object,
                                                               logTableMoq.Object, matterCenterServiceFunctionsMoq.Object, configRepository, environmentMoq.Object);

            var result = controller.GetConfigsForSPO("");

            Assert.True(result.Status > 0);
        }
示例#24
0
        public void TestInitialize()
        {
            _mockRepository = new Mock <IGigRepository>();

            var mockUoW = new Moq.Mock <IUnitOfWork>();

            mockUoW.SetupGet(u => u.Gigs).Returns(_mockRepository.Object);

            _controller = new GigsController(mockUoW.Object);
            _userId     = "1";
            _controller.MockCurrentUser(_userId, "*****@*****.**");
        }
示例#25
0
        public static void MockControllerContextForUser(this Controller controller, string userId)
        {
            var controllerContext = new Mock <ControllerContext>();
            var claim             = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId);

            var claimsIdentity = new ClaimsIdentity(new[] { claim });
            var principal      = new Moq.Mock <IPrincipal>();

            principal.SetupGet(x => x.Identity).Returns(claimsIdentity);
            controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);

            controller.ControllerContext = controllerContext.Object;
        }
示例#26
0
        public async Task OnGetLiveAsyncTest()
        {
            //Arrange
            var serverTiming_mock = new Moq.Mock <Lib.AspNetCore.ServerTiming.IServerTiming>();

            serverTiming_mock.SetupGet(m => m.Metrics).Returns(() =>
            {
                return(new List <Lib.AspNetCore.ServerTiming.Http.Headers.ServerTimingMetric>());
            });
            var environment_mock = new Moq.Mock <IHostingEnvironment>();

            environment_mock.SetupGet(m => m.WebRootPath).Returns(() =>
            {
                return(Path.Combine(ContentRoot, "wwwroot"));
            });


            //MjpgStreamerHttpClientHandler.AddressWithProxy = "https://127.0.0.1/webcamgalleryFake/Fakelive";
            using (var dummy_just_for_costructor = new MjpgStreamerHttpClientHandler(Configuration))
                using (var cache = new MemoryCache(new MemoryCacheOptions()))
                    using (var http_client_mock = new ImageMockHttpClient().GetMockClient(Configuration))
                    {
                        var client             = new MjpgStreamerHttpClient(http_client_mock, environment_mock.Object, cache, dummy_just_for_costructor);
                        WebCamImagesModel wcim = new WebCamImagesModel()
                        {
                            PageContext = this.LocalPageContext
                        };

                        //Act
                        var result = await wcim.OnGetLiveAsync(serverTiming_mock.Object, client);

                        //Assert
                        if (!string.IsNullOrEmpty(Configuration["LiveWebCamURL"]))
                        {
                            Assert.NotNull(result);
                            Assert.IsType <FileContentResult>(result);
                            Assert.True(MediaTypeNames.Image.Jpeg == ((FileContentResult)result).ContentType ||
                                        "image/png" == ((FileContentResult)result).ContentType);
                            Assert.NotNull(((FileContentResult)result).LastModified);
                        }
                        else
                        {
                            Assert.NotNull(result);
                            Assert.IsType <FileContentResult>(result);
                            Assert.True(MediaTypeNames.Image.Jpeg == ((FileContentResult)result).ContentType ||
                                        "image/png" == ((FileContentResult)result).ContentType);
                            Assert.NotNull(((FileContentResult)result).LastModified);
                        }
                        //MjpgStreamerHttpClientHandler.AddressWithProxy = null;
                    }
        }
示例#27
0
        public void should_return_ok_when_multiple_indexers_are_enabled()
        {
            GivenRssEnabled();
            GivenSearchEnabled();

            var indexer1 = Mocker.GetMock <IIndexer>();

            indexer1.SetupGet(s => s.SupportsRss).Returns(true);
            indexer1.SetupGet(s => s.SupportsSearch).Returns(true);

            var indexer2 = new Moq.Mock <IIndexer>();

            indexer2.SetupGet(s => s.SupportsRss).Returns(true);
            indexer2.SetupGet(s => s.SupportsSearch).Returns(false);

            Mocker.GetMock <IIndexerFactory>()
            .Setup(s => s.GetAvailableProviders())
            .Returns(new List <IIndexer> {
                indexer1.Object, indexer2.Object
            });

            Subject.Check().ShouldBeOk();
        }
示例#28
0
        protected Mock <IBookStorage> MakeMockStorage(string tempFolderPath, Func <HtmlDom> domGetter)
        {
            var storage = new Moq.Mock <IBookStorage>();

            storage.Setup(x => x.GetLooksOk()).Returns(true);

            storage.SetupGet(x => x.Dom).Returns(domGetter);
            storage.SetupGet(x => x.Key).Returns("testkey");
            storage.Setup(x => x.GetRelocatableCopyOfDom()).Returns(() => storage.Object.Dom.Clone()); // review: the real thing does more than just clone
            storage.Setup(x => x.MakeDomRelocatable(It.IsAny <HtmlDom>())).Returns(
                (HtmlDom x) => { return(x.Clone()); });                                                // review: the real thing does more than just clone

            storage.Setup(x => x.GetFileLocator()).Returns(() => _fileLocator.Object);

            MakeSamplePngImageWithMetadata(Path.Combine(tempFolderPath, "original.png"));
            storage.SetupGet(x => x.FolderPath).Returns(tempFolderPath);            // review: the real thing does more than just clone
            var metadata = new BookInfo(tempFolderPath, true);

            storage.SetupGet(x => x.BookInfo).Returns(metadata);
            storage.Setup(x => x.HandleRetiredXMatterPacks(It.IsAny <HtmlDom>(), It.IsAny <string>()))
            .Returns((HtmlDom dom, string y) => { return(y == "BigBook" ? "Factory" : y); });
            return(storage);
        }
示例#29
0
        public async Task JsonDataSourceTests_BadFile()
        {
            // Arrange
            var logger        = new Moq.Mock <ILogger <JsonPersonDataSource> >();
            var configuration = new Moq.Mock <IConfiguration>();

            configuration.SetupGet(c => c["PersonFileLocation"]).Returns(@".\TestData\example_data_bad.json");
            var sut = new JsonPersonDataSource(logger.Object, configuration.Object);

            // Act
            Func <Task> act = async() => await sut.Get();

            // Assert
            act.Should().Throw <JsonReaderException>();
        }
示例#30
0
        public void GetConfigsFromTableRep()
        {
            GeneralSettings genS = new GeneralSettings();

            genS.CloudStorageConnectionString = _fixture.Configuratuion.GetSection("General").GetSection("CloudStorageConnectionString").Value.ToString();
            var m = new Moq.Mock <IOptions <GeneralSettings> >();
            var l = new Moq.Mock <IOptions <UIConfigSettings> >();

            m.SetupGet(g => g.Value).Returns(genS);
            m.SetupAllProperties();


            ConfigRepository configRepository = new ConfigRepository(null, m.Object, l.Object);
            var response = configRepository.GetConfigEntities("");
        }
示例#31
0
        public void TickTaskWithRemainingTime()
        {
            var result = new Moq.Mock<ITaskResult>(MockBehavior.Strict);
            var mock = new Moq.Mock<ITask>(MockBehavior.Strict);

            mock.Setup(x => x.Execute()).Returns(result.Object);
            result.SetupGet(f => f.TimeRemaining).Returns(1);

            var queue = new TaskQueue();
            queue.Add(mock.Object);

            var count = queue.Tick();
            Assert.That(count, Is.EqualTo(0));
            Assert.That(queue.Count, Is.EqualTo(1));
        }
示例#32
0
        public async Task JsonDataSourceTests_ExampleFileProcessed()
        {
            // Arrange
            var logger        = new Moq.Mock <ILogger <JsonPersonDataSource> >();
            var configuration = new Moq.Mock <IConfiguration>();

            configuration.SetupGet(c => c["PersonFileLocation"]).Returns(@".\TestData\example_data.json");
            var sut = new JsonPersonDataSource(logger.Object, configuration.Object);

            // Act
            var data = await sut.Get();

            // Assert
            data.Count.Should().Be(6);
        }
        public void ReadsCorrectly()
        {
            // arrange
            var converter = new EnumConverter();
            var reader1 = new Moq.Mock<JsonReader>();
            reader1.SetupGet(x => x.Value).Returns(null);
            var reader2 = new Moq.Mock<JsonReader>();
            reader2.SetupGet(x => x.Value).Returns("0");
            var reader3 = new Moq.Mock<JsonReader>();
            reader3.SetupGet(x => x.Value).Returns("1");

            // act
            var object1 = converter.ReadJson(reader1.Object, typeof(System.ConsoleColor), null, null);
            var object2 = converter.ReadJson(reader1.Object, typeof(System.ConsoleColor?), null, null);
            var object3 = converter.ReadJson(reader2.Object, typeof(System.ConsoleColor), null, null);
            var object4 = converter.ReadJson(reader3.Object, typeof(System.ConsoleColor), null, null);

            // assert
            Assert.IsNull(object1);
            Assert.IsNull(object2);
            Assert.AreEqual(System.ConsoleColor.Black, (System.ConsoleColor)object3);
            Assert.AreEqual(System.ConsoleColor.DarkBlue, (System.ConsoleColor)object4);
        }
示例#34
0
        public void ReadsCorrectly()
        {
            // arrange
            var converter = new BoolConverter();
            var reader1 = new Moq.Mock<JsonReader>();
            reader1.SetupGet(x => x.Value).Returns(null);
            var reader2 = new Moq.Mock<JsonReader>();
            reader2.SetupGet(x => x.Value).Returns("0");
            var reader3 = new Moq.Mock<JsonReader>();
            reader3.SetupGet(x => x.Value).Returns("1");

            // act
            var object1 = converter.ReadJson(reader1.Object, typeof(bool), null, null);
            var object2 = converter.ReadJson(reader1.Object, typeof(bool?), null, null);
            var object3 = converter.ReadJson(reader2.Object, typeof(bool), null, null);
            var object4 = converter.ReadJson(reader3.Object, typeof(bool), null, null);

            // assert
            Assert.IsAssignableFrom<bool>(object1);
            Assert.IsFalse((bool)object1);
            Assert.IsNull(object2);
            Assert.IsFalse((bool)object3);
            Assert.IsTrue((bool)object4);
        }
        internal MockResults SetupHttpAbstractionMocking()
        {
            var results = new MockResults();
            // Locate the test manager so we can override the lower layer.
            var manager = ServiceLocator.Instance.Locate<IServiceLocationIndividualTestManager>();

            // Create a Mock of the HTTP layer response.
            var moqResponse = new Moq.Mock<IHttpResponseMessageAbstraction>(MockBehavior.Loose);
            // Always return 200 OK
            moqResponse.SetupGet(res => res.StatusCode)
                       .Returns(HttpStatusCode.OK);

            // Create a mock of the Request client.
            var moqClient = new Moq.Mock<IHttpClientAbstraction>(MockBehavior.Loose);

            // Mock the return to set the request headers.
            moqClient.SetupGet(client => client.RequestHeaders)
                     .Returns(() => results.Headers);

            // Mock the return to set the request uri.
            moqClient.SetupGet(client => client.RequestUri)
                     .Returns(() => results.RequestUri);

            // Mock the return to set the request uri.
            moqClient.SetupSet(abstraction => abstraction.RequestUri = It.IsAny<Uri>()).Callback<Uri>(uri => results.RequestUri = uri);

            // Mock the return to set the http method.
            moqClient.SetupGet(client => client.Method)
                     .Returns(() => results.Method);

            // Mock the return to set the http method.
            moqClient.SetupSet(abstraction => abstraction.Method = It.IsAny<HttpMethod>()).Callback<HttpMethod>(method => results.Method = method);

            // Mock the return to set the content.
            moqClient.SetupGet(client => client.Content)
                     .Returns(() => results.Content);

            moqClient.SetupSet(abstraction => abstraction.Content = It.IsAny<HttpContent>()).Callback<HttpContent>(content => results.Content = content);

            // Mock the SendAsync method (to just return the response object previously created).
            moqClient.Setup(c => c.SendAsync())
                     .Returns(() => Task.Run(() =>
                     {
                         results.SendAsyncCalled = true;
                         return moqResponse.Object;
                     }));

            // Mock the factory to return our mock client.
            var moqFactory = new Moq.Mock<IHttpClientAbstractionFactory>();

            // Overload both create methods.
            moqFactory.Setup(fac => fac.Create(It.IsAny<X509Certificate2>(), It.IsAny<HDInsight.IAbstractionContext>(), false))
                      .Returns(() => moqClient.Object);
            moqFactory.Setup(fac => fac.Create(It.IsAny<HDInsight.IAbstractionContext>(), false))
                      .Returns(() => moqClient.Object);

            // Override the factory in the Service Locator (for this test only).
            manager.Override<IHttpClientAbstractionFactory>(moqFactory.Object);
           
            return results;
        }
示例#36
0
            public EventControllerBuilder WithUserLogged()
            {
                var httpContext = new Mock<HttpContext>();

                var controllerContext = new Mock<ControllerContext>();
                var principal = new Moq.Mock<ClaimsPrincipal>();


                principal.Setup(p => p.IsInRole("Administrator")).Returns(true);
                principal.SetupGet(x => x.Identity.Name).Returns("userName");

                httpContext.Setup(x => x.User).Returns(principal.Object);
                controllerContext.Object.HttpContext = httpContext.Object;
                _controllerContext = controllerContext.Object;

                return this;
            }
        public void ProcessLimitsTest(
      string configurationName,
      SLimits limits, 
      bool logStatistic, 
      int apiUsageThreshold, 
      int dataStorageThreshold,
      Times[] result)
        {
            var mockedApiDailyRequestsLoger = new Moq.Mock<ILimitLoger>();
              if (limits != null)
              {
            var apiDailyRequestsLoger = new ApiDailyRequestsLoger(configurationName, limits.DailyApiRequests);
            mockedApiDailyRequestsLoger.SetupGet(p => p.UsedAmount).Returns(apiDailyRequestsLoger.UsedAmount);
            mockedApiDailyRequestsLoger.SetupGet(p => p.UsedPercents).Returns(apiDailyRequestsLoger.UsedPercents);
              }

              mockedApiDailyRequestsLoger.Setup(m => m.LogPointWarning()).Verifiable();
              mockedApiDailyRequestsLoger.Setup(m => m.LogHasReachedError()).Verifiable();

              var mockedDataStorageLoger = new Moq.Mock<ILimitLoger>();
              if (limits != null)
              {
            var dataStorageLoger = new ApiDailyRequestsLoger(configurationName, limits.DataStorageMb);
            mockedDataStorageLoger.SetupGet(p => p.UsedAmount).Returns(dataStorageLoger.UsedAmount);
            mockedDataStorageLoger.SetupGet(p => p.UsedPercents).Returns(dataStorageLoger.UsedPercents);
              }

              mockedDataStorageLoger.Setup(m => m.LogPointWarning()).Verifiable();
              mockedDataStorageLoger.Setup(m => m.LogHasReachedError()).Verifiable();

              var mockedLoger = new Moq.Mock<ILimitsLoger>();
              mockedLoger.SetupGet(p => p.ApiDailyRequestsLoger).Returns(mockedApiDailyRequestsLoger.Object);
              mockedLoger.SetupGet(p => p.DataStorageLoger).Returns(mockedDataStorageLoger.Object);
              mockedLoger.Setup(m => m.LogStatisticInfo()).Verifiable();
              mockedLoger.Setup(m => m.LogInformationAreNotAvailableWarning()).Verifiable();

              var agent = new LimitsAgent();
              agent.LogStatistic = logStatistic;
              agent.ApiUsageThreshold = apiUsageThreshold;
              agent.DataStorageThreshold = dataStorageThreshold;
              var logerField = typeof(LimitsAgent).GetField("loger", BindingFlags.Instance | BindingFlags.NonPublic);
              if (logerField != null)
              {
            logerField.SetValue(agent, mockedLoger.Object);
              }

              agent.ProcessLimits(limits);

              mockedLoger.Verify(m => m.LogStatisticInfo(), result[0]);
              mockedLoger.Verify(m => m.LogInformationAreNotAvailableWarning(), result[1]);
              mockedApiDailyRequestsLoger.Verify(m => m.LogPointWarning(), result[2]);
              mockedApiDailyRequestsLoger.Verify(m => m.LogHasReachedError(), result[3]);
              mockedDataStorageLoger.Verify(m => m.LogPointWarning(), result[4]);
              mockedDataStorageLoger.Verify(m => m.LogHasReachedError(), result[5]);
        }
示例#38
-1
        public void Setup()
        {
            var httpContextBaseMock = new Moq.Mock<HttpContextBase>();

            var httpRequestBase = new Moq.Mock<HttpRequestBase>();
            httpRequestBase.SetupGet(r => r.ApplicationPath).Returns(@"\");
            httpContextBaseMock.SetupGet(c => c.Items).Returns(new Dictionary<string, object>());
            httpRequestBase.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());
            httpRequestBase.Object.Cookies.Add(new HttpCookie(GlimpseConstants.CookieModeKey, "On"));

            httpContextBaseMock.SetupGet(c => c.Request).Returns(httpRequestBase.Object);
            httpContext = httpContextBaseMock.Object;
        }