예제 #1
0
        public void OnMouseLeftButtonUp_NodesShouldBeConnectedFromSourceToDestination()
        {
            var thumbMock = Mock.Create<ConnectorThumb>(Constructor.Mocked);
            var privateAccessor = new PrivateAccessor(thumbMock);

            //Arrange
            Mock.NonPublic.Arrange(thumbMock, "OnMouseLeftButtonUp", ArgExpr.IsAny<MouseButtonEventArgs>()).CallOriginal();

            var dcMock = Mock.Create<ExpressionConnectorViewModel>();
            Mock.Arrange(() => dcMock.ConnectorType).Returns(ConnectorType.In);
            Mock.Arrange(() => dcMock.Item.CreateConnection(Arg.IsAny<IDiagramItem>(), Arg.IsAny<IDiagramItem>()))
                .Returns(Mock.Create<ExpressionConnection>(Constructor.Mocked, Behavior.Loose));
            Mock.Arrange(() => thumbMock.DataContext).Returns(dcMock);

            var panelMock = Mock.Create<DiagramPanel>(Constructor.Mocked);
            Mock.Arrange(() => DiagramPanel.GetParentPanel<DiagramPanel>(thumbMock)).Returns(panelMock);

            var panelDcMock = Mock.Create<DiagramViewModel>();
            Mock.Arrange(() => panelDcMock.Items).Returns(new Collection<IDiagramItemViewModel>());
            Mock.Arrange(() => panelMock.DataContext).Returns(panelDcMock);

            var connectionEndMock = Mock.Create<ExpressionConnectorViewModel>();
            Mock.Arrange(() => connectionEndMock.CreateConnectionTo(Arg.IsAny<IDiagramItemViewModel>())).CallOriginal();
            Mock.Arrange(() => connectionEndMock.CanConnectTo(Arg.IsAny<IDiagramItemViewModel>(), Arg.IsAny<ICollection<IDiagramItemViewModel>>())).Returns(ConnectivityState.Allow);
            Mock.Arrange(() => panelMock.GetViewModelByLocation<IDiagramItemViewModel>(Arg.IsAny<Point>())).Returns(connectionEndMock);

            privateAccessor.SetField("_isDragging", true);

            //Act
            privateAccessor.CallMethod("OnMouseLeftButtonUp", Mock.Create<MouseButtonEventArgs>());

            //Assert
            IConnectionViewModel newConnection = null;

            try
            {
                newConnection = panelDcMock.Items.ToList()[0] as IConnectionViewModel;
            }
            catch (Exception)
            {                
                Assert.Fail("No connections where created");
                return;
            }

            Assert.AreEqual(1, panelDcMock.Items.Count);

            if (newConnection != null)
            {
                Assert.AreEqual(connectionEndMock, newConnection.Source);
                Assert.AreEqual(dcMock, newConnection.Destination);
            }
            else
                Assert.Fail("Type of the object does not inherit IConnectionViewModel");
        }
        public void RefreshTests()
        {
            // arrange
            var vm = new SelectPersonViewModel();

            var getFilterWasCalled = false;
            Mock.NonPublic.Arrange<MobileObservableCollection<IFilterDescriptor>>(vm, "GetFilter").DoInstead(() => getFilterWasCalled = true);

            var dynamicTypeManager = Mock.Create<IDynamicTypeManager>(Behavior.CallOriginal);

            Mock.Arrange(() => dynamicTypeManager.GetCustomType(Constants.AccountProcessName, "LinkablePersonList", true))
                .DoInstead(() => Assert.IsTrue(vm.IsBusy))
                    .Returns(typeof(object));

            vm.TheDynamicTypeManager = dynamicTypeManager;

            var account = Mock.Create<IAccount>(Behavior.Loose);
            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_selectedAccount", account);

            var basePersonList = Mock.Create<IList>(Behavior.Loose);

            Mock.Arrange(() => MethodCaller.CallFactoryMethod(Arg.IsAny<Type>(), "Get__AccountLinkablePersonListAsync", Arg.AnyInt, Arg.IsAny<int?>(), Arg.IsAny<PagedCriteria>()))
                .Returns(() =>
                    {
                        var tcs = new TaskCompletionSource<IList>();
                        tcs.SetResult(basePersonList);
                        return tcs.Task;
                    });

            // act
            privateAccessor.CallMethod("Refresh");

            // assert
            Assert.IsTrue(getFilterWasCalled);
            Assert.AreEqual(basePersonList, vm.PersonList);
            Assert.IsFalse(vm.IsBusy);
        }
예제 #3
0
        public void PropertiesTests()
        {
            //Testing public properties that have both getter and setter
            var vm = new GageRRFieldViewModel();
            TestsHelper.TestPublicDeclaredPropertiesGetSet(vm, true);

            var vmPrivateAccessor = new PrivateAccessor(vm);

            var dataGroupingItemMock = Mock.Create<IInfoClass>();
            Mock.Arrange(() => dataGroupingItemMock.Id).Returns(3);
            vmPrivateAccessor.SetField("_dataGroupingItem", dataGroupingItemMock);

            Mock.SetupStatic(typeof (LanguageService), Behavior.Loose);
            Mock.Arrange(() => LanguageService.Translate("Label_DataGroupingItemId")).Returns("Data Grouping Item");

            Assert.AreEqual("Data Grouping Item:  3", vm.DataGroupingItemIdLabel);
            Assert.IsTrue(vm.ShowItemIdLabel);

            Mock.NonPublic.Arrange(vm, "ExecuteShowItemSelector", ArgExpr.IsAny<object>()).DoNothing().MustBeCalled();
            vm.ShowItemSelectorCommand.Execute(null);

            Mock.NonPublic.Assert(vm, "ExecuteShowItemSelector", Occurs.Once(), ArgExpr.IsAny<object>());
        }
예제 #4
0
        public void UnlockCommand_WhenExecutes_SetsCorrectUnlockErrorMessage()
        {
            var vm = new MainViewModel { IsLocked = true, UnlockErrorMessage = "error", Password = "******", Username = "******"};
            Mock.Arrange(() => ApplicationContext.User.Identity).Returns(new MQ1Identity { UserName = vm.Username });
            var timer = CreateTimer();
            var mainVmPrivateAccessor = new PrivateAccessor(vm);
            mainVmPrivateAccessor.SetField("_sessionInactivityTimer", timer);
            var errorMessage = TestsHelper.GetRandomString();

            Mock.Arrange(
                () =>
                    AuthenticateUserCommand.BeginExecute(Arg.IsAny<string>(), vm.Password, Arg.IsAny<int>(),
                        Arg.IsAny<EventHandler<DataPortalResult<AuthenticateUserCommand>>>(), Arg.IsAny<bool>()))
                .DoInstead(
                    (string user, string password, int id,
                        EventHandler<DataPortalResult<AuthenticateUserCommand>> callback, bool allow) =>
                        callback(null, CreateAuthenticateUserDataPortalResult(errorMessage)));

            //Act
            vm.UnlockCommand.Execute(null);

            //Assert
            Assert.AreEqual(errorMessage, vm.UnlockErrorMessage);
        }
예제 #5
0
        public void ProcessRequest_ResponseIsEmptyStream()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "FileId", "1" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var dynamicTypeManager = Mock.Create<IDynamicTypeManager>(Behavior.CallOriginal);

            var fileProcess = Mock.Create<IFileProcess>(Behavior.Loose);
            fileProcess.FileName = "77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt";

            Mock.Arrange(() => dynamicTypeManager.GetEditableRoot<IFileProcess>(Constants.FileProcessName, 1)).
                Returns<string, int>((processName, id) => fileProcess);

            handler.TheDynamicTypeManager = dynamicTypeManager;

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt");

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);
            
            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var called = false;
            Mock.Arrange(() => context.Response.Write("The file was deleted manually, or maybe, path is incorrect\r\nFull address is: http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt")).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.AreEqual("text/plain", context.Response.ContentType);
            Assert.IsTrue(called);
        }
예제 #6
0
        public void OnApplyTemplateTest()
        {
            var spreadsheet = Mock.Create<SpreadsheetView>(Behavior.CallOriginal);
            var privateAccessor = new PrivateAccessor(spreadsheet);

            spreadsheet.OnApplyTemplate();
            //FillItemsSource can not be called if ItemsSource is null
            Mock.NonPublic.Assert(spreadsheet, "FillItemsSource", Occurs.Never(), ArgExpr.IsAny<IEnumerable>());
            Assert.IsTrue((bool)privateAccessor.GetField("_templateApplied"));

            privateAccessor.SetField("_templateApplied", false);
            spreadsheet.ItemsSource = new List<TestData>();
            spreadsheet.OnApplyTemplate();
            //AutoGenerateColumns is true and Columns is not null
            Mock.NonPublic.Assert(spreadsheet, "FillItemsSource", Occurs.Once(), ArgExpr.IsAny<IEnumerable>());
            Assert.IsTrue((bool)privateAccessor.GetField("_templateApplied"));

            spreadsheet.Columns = null;
            spreadsheet.OnApplyTemplate();
            //AutoGenerateColumns is true and Columns is null
            Mock.NonPublic.Assert(spreadsheet, "FillItemsSource", Occurs.Once(), ArgExpr.IsAny<IEnumerable>());
            Assert.IsTrue((bool)privateAccessor.GetField("_templateApplied"));

            spreadsheet.Columns = new SpreadsheetColumnCollection();
            spreadsheet.AutoGenerateColumns = false;
            spreadsheet.OnApplyTemplate();
            //AutoGenerateColumns is false but Columns collection is empty
            Mock.NonPublic.Assert(spreadsheet, "FillItemsSource", Occurs.Once(), ArgExpr.IsAny<IEnumerable>());
            Assert.IsTrue((bool)privateAccessor.GetField("_templateApplied"));
        }
        public void PopulateUdp_SetFilterDefinition_Test()
        {
            //Mock step edit
            var stepEditMock = Mock.Create<GageRROptionsStepEdit>(Behavior.CallOriginal);
            Mock.Arrange(() => stepEditMock.SampleFilterDefinition).CallOriginal();

            //Create view model
            var vm = Mock.Create<GageRROptionsStepViewModel>(Constructor.Mocked, Behavior.CallOriginal);
            Mock.Arrange(() => vm.Data).Returns(stepEditMock);

            //Arrange
            Mock.Arrange(() => vm.UdpList).Returns(
                new ObservableCollection<FilterDescriptorDecorator> { Mock.Create<FilterDescriptorDecorator>(Constructor.Mocked) });
            var vmPrivateAccessor = new PrivateAccessor(vm);

            var outerFilterDescriptorMock = Mock.Create<IFilterDescriptor>(Behavior.Loose);
            var innerFilterDescriptorMock = Mock.Create<IFilterDescriptor>(Behavior.Loose);

            var innerFilterValueMock = Mock.Create<FilterValue>(Behavior.Loose);
            Mock.Arrange(() => innerFilterDescriptorMock.Value).Returns(innerFilterValueMock);

            Mock.Arrange(() => FilterDescriptor.FromJSON(Arg.IsAny<string>()))
                .Returns(outerFilterDescriptorMock);

            var udpFilters = new ObservableCollection<IFilterDescriptor> {innerFilterDescriptorMock};

            Mock.Arrange(() => outerFilterDescriptorMock.GetAllUdpDescriptors())
                .Returns(udpFilters);

            Mock.Arrange(() => FilteringUtils.LoadFilterAdditionalParameters(
                    Arg.IsAny<ObservableCollection<FilterDescriptorDecorator>>(), 
                    Arg.IsAny<PublishedProcessWithFiltersInfo>()))
                .DoNothing().MustBeCalled();

            //Act: Call PopulateUdp method
            vmPrivateAccessor.CallMethod("PopulateUdp", "FilterDefinition");

            //Assert
            Mock.Assert(() => FilteringUtils.LoadFilterAdditionalParameters(
                            Arg.IsAny<ObservableCollection<FilterDescriptorDecorator>>(),
                            Arg.IsAny<PublishedProcessWithFiltersInfo>())
                        , Occurs.Once());
            Assert.AreEqual(1, vm.UdpList.Count);
            Assert.AreEqual(innerFilterValueMock, vm.UdpList[0].Value);


            //Arrange
            Mock.Arrange(() => outerFilterDescriptorMock.ToJSON()).Returns("Definition");

            //Act: Invoke PropertyChanged event of FilterValue object
            vmPrivateAccessor.SetField("_isLoading", false);
            Mock.Raise(() => innerFilterValueMock.PropertyChanged += null, Arg.IsAny<object>(), new PropertyChangedEventArgs(string.Empty));

            Assert.AreEqual("Definition", vm.FilterDefinition);
            Mock.Assert(() => vm.GetProcessedFilter(), Occurs.Once());
        }
예제 #8
0
        public void DownloadImageCommand()
        {
            // arrange
            var vm = new ImageFieldViewModel();

            var saveFileDialog = Mock.Create<SaveFileDialog>(Behavior.CallOriginal);
            Mock.Arrange(() => saveFileDialog.ShowDialog()).Returns(false);

            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_saveFileDialog", saveFileDialog);

            Mock.NonPublic.Arrange<bool>(vm, "IsImageExists", new object[] { ArgExpr.IsAny<object>() }).Returns(true);

            var editableRoot = Mock.Create<IEditableRoot>(Behavior.Loose);
            Mock.Arrange(() => editableRoot.ProcessName).Returns("eCar_p");
            Mock.Arrange(() => editableRoot.Id).Returns(1);

            Mock.Arrange(() => vm.ParentModel).Returns(editableRoot);

            Mock.Arrange(() => vm.Property).Returns(GetType().GetProperty("Image2"));

            // act
            try
            {
                vm.DownloadImageCommand.Execute(null);
            }
            catch(Exception ex)
            {
                // assert
                Assert.Fail("Expected no exception, but got: " + ex.Message);
            }

            // arrange
            Mock.Arrange(() => saveFileDialog.ShowDialog()).Returns(true);

            Mock.Arrange(() => saveFileDialog.OpenFile()).Returns(new MemoryStream());

            var array = new byte[8 * 1024 + 1];
            for (var i = 0; i < array.Length; i++)
            {
                array[i] = new byte();
            }

            vm.Value = array;

            var popupFactory = new PopupFactory();
            var notifySuccessCalled = false;
            Mock.Arrange(() => popupFactory.NotifySuccess(LanguageService.Translate("Msg_SuccessfullySaved"), "Popup_Success")).DoInstead(() => notifySuccessCalled = true);

            vm.ThePopupFactory = popupFactory;

            // act
            vm.DownloadImageCommand.Execute(null);

            // assert
            Assert.IsTrue(notifySuccessCalled);
            Assert.IsNull(privateAccessor.GetField("_saveFileDialog"));
        }
예제 #9
0
        public void ElementExporting_Cell()
        {
            // arrange
            var exportUtility = new ExportUtility();
            var exportViewModel = new ExportOptionsViewModel
            {
                ExportFileType = ExportFileType.Excel
                
            };

            var model = exportViewModel;
            exportUtility.TheExportOptionsViewModel = new Lazy<ExportOptionsViewModel>(() => model);

            var e = Mock.Create<GridViewElementExportingEventArgs>(Behavior.Loose);
            var parameters = new GridViewHtmlVisualExportParameters();
            Mock.Arrange(() => e.VisualParameters).Returns(parameters);
            Mock.Arrange(() => e.Element).Returns(ExportElement.Cell);

            var column = new GridViewDataColumn { UniqueName = "Notes" };
            Mock.Arrange(() => e.Context).Returns(column);

            var privateAccessor = new PrivateAccessor(exportUtility);

            var accessDeniedProperties = new List<string> { "Notes" };
            privateAccessor.SetField("_accessDeniedProperties", accessDeniedProperties);

            // act
            privateAccessor.CallMethod("ElementExporting", new[] { new object(), e });

            // assert
            Assert.AreEqual("<Blocked>", e.Value);
            Assert.AreEqual(Colors.Red, parameters.Foreground);

            // arrange
            accessDeniedProperties.Clear();
            e.Value = "<Rich Text>";

            // act
            privateAccessor.CallMethod("ElementExporting", new[] { new object(), e });

            // assert
            Assert.AreEqual(Colors.Blue, parameters.Foreground);

            // arrage
            e.Value = new byte[] { };

            exportViewModel = new ExportOptionsViewModel
            {
                RowForeground = Colors.Yellow,
                ExportFileType = ExportFileType.Excel
                
            };

            exportUtility.TheExportOptionsViewModel = new Lazy<ExportOptionsViewModel>(() => exportViewModel);

            // act
            privateAccessor.CallMethod("ElementExporting", new[] { new object(), e });
            
            // assert
            Assert.AreEqual("binary data", e.Value);
            Assert.AreEqual(Colors.Yellow, parameters.Foreground);
        }
예제 #10
0
        public void EndWebRequest()
        {
            // arrange
            var vm = new FieldFileViewModel();

            var asyncResult = Mock.Create<IAsyncResult>(Behavior.CallOriginal);
            var httpWebRequest = Mock.Create<HttpWebRequest>(Behavior.CallOriginal);
            var httpWebResponse = Mock.Create<HttpWebResponse>(Behavior.Loose);

            Mock.Arrange(() => httpWebRequest.EndGetResponse(asyncResult)).Returns(httpWebResponse);

            Mock.Arrange(() => asyncResult.AsyncState).Returns(httpWebRequest);

            Mock.Arrange(() => Deployment.Current.Dispatcher.BeginInvoke(Arg.IsAny<Action>())).DoInstead<Action>(a => a());

            var saveFileDialog = Mock.Create<SaveFileDialog>(Behavior.CallOriginal);

            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_dialog", saveFileDialog);

            // act
            privateAccessor.CallMethod("EndWebRequest", new object[] { asyncResult });

            // assert
            Assert.IsNull(privateAccessor.GetField("_dialog"));
            Assert.AreEqual(FileControlMode.Error, vm.CurrentState);

            // arrange
            Mock.Arrange(() => httpWebResponse.ContentLength).Returns(Constants.FileProcessBufferSize);

            var outputStream = Mock.Create<Stream>(Behavior.Loose);

            Mock.Arrange(() => saveFileDialog.OpenFile()).Returns(outputStream);
            privateAccessor.SetField("_dialog", saveFileDialog);

            var task = new Task(() => { });
            task.RunSynchronously();

            Mock.Arrange(() => Task.Factory.StartNew(Arg.IsAny<Action>())).DoInstead<Action>(a => a()).Returns(() => task);

            var inputStream = Mock.Create<Stream>(Behavior.Loose);

            var exit = false;
            Mock.Arrange(() => inputStream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
            {
                if (!exit)
                {
                    exit = true;
                    return Constants.FileProcessBufferSize;
                }

                return 0;
            });

            Mock.Arrange(() => httpWebResponse.GetResponseStream()).Returns(inputStream);

            var inputStreamWasClosed = false;
            Mock.Arrange(() => inputStream.Close()).DoInstead(() => inputStreamWasClosed = true);

            var responseWasClosed = false;
            Mock.Arrange(() => httpWebResponse.Close()).DoInstead(() => responseWasClosed = true);

            var outputStreamWasClosed = false;
            Mock.Arrange(() => outputStream.Close()).DoInstead(() => outputStreamWasClosed = true);

            // act
            privateAccessor.CallMethod("EndWebRequest", new object[] { asyncResult });

            // assert
            Assert.AreEqual(Constants.FileProcessBufferSize, vm.ProgressBarMaximumValue);
            Assert.AreEqual(Constants.FileProcessBufferSize, vm.ProgressBarValue);
            Assert.AreEqual("Downloading 100%" + Environment.NewLine, vm.DownloadPercent);

            Assert.IsTrue(inputStreamWasClosed);

            Assert.IsTrue(responseWasClosed);
            Assert.IsTrue(outputStreamWasClosed);
            Assert.AreEqual(FileControlMode.Locked, vm.CurrentState);
            Assert.IsNull(privateAccessor.GetField("_dialog"));
        }
예제 #11
0
        public void OnUploadCanceled()
        {
            // arrange
            var vm = new FieldFileViewModel();

            var fileProcess = Mock.Create<IFileProcess>(Behavior.Loose);
            fileProcess.IsUploading = true;
            Mock.NonPublic.Arrange<IFileProcess>(vm, "CurrentFileProcess").Returns(fileProcess);

            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_stopExecuteUploadCanceledEvent", true);

            // act
            vm.OnUploadCanceled(null, null);

            // assert
            Assert.IsTrue(fileProcess.IsUploading);

            // arrange
            privateAccessor.SetField("_stopExecuteUploadCanceledEvent", false);

            var beginCancelUploadingCalled = false;
            Mock.Arrange(() => fileProcess.BeginCancelUploading(Arg.IsAny<Action<object, IDataPortalResult>>()))
                .DoInstead(() => beginCancelUploadingCalled = true);

            // act
            vm.OnUploadCanceled(null, null);

            // assert
            Assert.IsFalse(fileProcess.IsUploading);
            Assert.IsTrue(beginCancelUploadingCalled);
            Assert.AreEqual(FileControlMode.Upload, vm.CurrentState);
        }
예제 #12
0
        public void ProcessRequest_ReportFileName()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_reportsPath", "D:\\Reports" );

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "ReportFileName", "1.trdx" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var called = false;
            Mock.NonPublic.Arrange(handler, "ReadFile", new object[] { context, @"D:\Reports\1.trdx" }).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(called);
        }
        public void FilterOptionsCommandTest()
        {
            //Create view model
            var vm = Mock.Create<GageRROptionsStepViewModel>(Constructor.Mocked, Behavior.CallOriginal);

            //Arrange
            var processFieldList = new List<ProcessField>();
            Mock.NonPublic.Arrange<IList<ProcessField>>(vm, "GetProcessFields", ArgExpr.IsAny<Type>()).Returns(processFieldList);
            Mock.Arrange(() => vm.FilterOptionsVM)
                .Returns(new Lazy<FilterOptionsViewModel>(() => 
                            Mock.Create<FilterOptionsViewModel>(Constructor.Mocked, Behavior.Loose)));

            var filterOptionsMock = vm.FilterOptionsVM.Value;
            Mock.NonPublic.Arrange(filterOptionsMock, "RaisePropertyChanged", ArgExpr.IsAny<Expression<Func<IList<ProcessField>>>>()).DoNothing();
            Mock.Arrange(() => filterOptionsMock.CleanUp()).DoNothing().MustBeCalled();
            Mock.Arrange(() => filterOptionsMock.ProcessFields).CallOriginal();
            Mock.ArrangeSet(() => filterOptionsMock.ProcessFields = Arg.IsAny<IList<ProcessField>>()).CallOriginal();
            filterOptionsMock.ProcessFields = null;
            filterOptionsMock.IsUdpEditMode = false;
            filterOptionsMock.FilterDescriptor = null;
            filterOptionsMock.ShowUdPs = true;
            filterOptionsMock.ShowProcessFields = false;

            var filterDescriptorMock = Mock.Create<IFilterDescriptor>(Behavior.Loose);
            Mock.NonPublic.Arrange(vm, "OnFilterOptionsShowed", filterDescriptorMock).DoNothing().MustBeCalled();

            var popupMock = PopupMock.Create();
            vm.ThePopupFactory = popupMock.TheLazyPopupFactory;

            var popupFactory = vm.ThePopupFactory.Value;
            var popupBuilder = popupMock.ThePopupBuilder;

            Mock.Arrange(() => popupBuilder.SetCustomViewModel(filterOptionsMock)).Returns(popupBuilder).MustBeCalled();
            Mock.Arrange(() => popupBuilder.Show(Arg.IsAny<Action>(), Arg.IsAny<Func<bool>>()))
                .Returns<Action, Func<bool>>((onOK, onCancel) =>
                {
                    var pa = new PrivateAccessor(popupMock);
                    pa.SetField("_showCalled", true);

                    Mock.Arrange(() => popupBuilder.OkCommand).Returns(new ActionCommand<object>(obj => onOK()));
                    return popupBuilder;
                });

            //Act: Execute FilterOptionsCommand command
            vm.FilterOptionsCommand.Execute(filterDescriptorMock);

            //Assert
            Assert.AreEqual(processFieldList, filterOptionsMock.ProcessFields);
            Assert.IsTrue(filterOptionsMock.IsUdpEditMode);
            Mock.AssertSet(() => filterOptionsMock.FilterDescriptor = Arg.IsAny<IFilterDescriptor>());
            Assert.IsFalse(filterOptionsMock.ShowUdPs);
            Assert.IsTrue(filterOptionsMock.ShowProcessFields);

            Mock.Assert(() => popupFactory.Popup(), Occurs.Once());
            Mock.Assert(() => popupBuilder.SetCustomViewModel(filterOptionsMock), Occurs.Once());
            Mock.Assert(() => popupBuilder.SetIsModal(true), Occurs.Once());
            Mock.Assert(() => popupBuilder.SetCaption(Arg.IsAny<string>()), Occurs.Once());
            Mock.Assert(() => popupBuilder.SetPosition(PopupPosition.Center), Occurs.Once());
            popupMock.AssertShow();

            //Press OK
            popupBuilder.OkCommand.Execute(null);

            Mock.NonPublic.Assert(vm, "OnFilterOptionsShowed", Occurs.Once(), filterDescriptorMock);
        }
예제 #14
0
        public void ThumbnailViewer_OnLoaded_Test()
        {
            var arg = Mock.Create<RoutedEventArgs>(Behavior.Loose);
            var mainMenu = new MainMenuMetroView();
            var privateAccessor = new PrivateAccessor(mainMenu);

            Mock.Arrange(() => Application.Current.Host.Content.ActualWidth).Returns(10);

            privateAccessor.SetField("thumbnailScrolltTimerStarted", false);

            privateAccessor.CallMethod("ThumbnailViewer_OnLoaded", new object[] { null, arg });

            Assert.IsTrue((bool)privateAccessor.GetField("thumbnailScrolltTimerStarted"));
        }
예제 #15
0
        public void ThumbnailViewer_OnMouseLeftButtonDown_Test()
        {

            var arg = Mock.Create<MouseButtonEventArgs>(Behavior.Loose);
            var mainMenu = new MainMenuMetroView();
            var privateAccessor = new PrivateAccessor(mainMenu);

            privateAccessor.SetField("thumbnailScrolltTimerStarted", true);

            privateAccessor.CallMethod("ThumbnailViewer_OnMouseLeftButtonDown", new object[] { null, arg });

            Assert.IsFalse((bool)privateAccessor.GetField("isLeaved"));
        }
예제 #16
0
        public void ThumbnailViewer_OnMouseLeave_Test()
        {
            var arg = Mock.Create<MouseEventArgs>(Behavior.Loose);
            var mainMenu = new MainMenuMetroView();
            var privateAccessor = new PrivateAccessor(mainMenu);

            privateAccessor.SetField("isLeaved", false);

            privateAccessor.CallMethod("ThumbnailViewer_OnMouseLeave", new object[] { null, arg });

            Assert.IsTrue((bool)privateAccessor.GetField("isLeaved"));
        }
예제 #17
0
        public void ThumbnailScrollTimerTick_Non_isLeaved_Test()
        {
            var arg = Mock.Create<EventArgs>(Behavior.Loose);
            var mainMenu = new MainMenuMetroView();
            var privateAccessor = new PrivateAccessor(mainMenu);

            privateAccessor.SetField("isLeaved", false);

            privateAccessor.CallMethod("ThumbnailScrollTimerTick", new object[] { null, arg });

            Assert.IsFalse((bool)privateAccessor.GetField("isLeaved"));
            Assert.IsTrue((double)privateAccessor.GetField("acceleration") == 0.0);
        }
예제 #18
0
        public void OnAfterDataRefreshed()
        {
            var vm = GetNewSearchListVm();

            var infoClass = Mock.Create<IInfoClass>(Behavior.Loose);
            Mock.Arrange(() => vm.InfoListViewSource).ReturnsCollection(new Collection<IInfoClass> { infoClass });
            
            var exportUtility = new ExportUtility();

            var exportStartWasCalled = false;
            Mock.Arrange(() => exportUtility.ExportStart(Arg.AnyString, Arg.IsAny<GridViewDataControl>(), Arg.AnyString)).DoInstead(() => exportStartWasCalled = true);

            var refreshSearchListWasCalled = false;
            Mock.Arrange(() => vm.RefreshSearchList(Arg.IsAny<IFilterViewModel>())).DoInstead(() => refreshSearchListWasCalled = true);

            vm.TheExportUtility = new Lazy<ExportUtility>(() => exportUtility);

            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_tempPageSize", 25);
            privateAccessor.SetField("_tempPageIndex", 10);

            // act
            privateAccessor.CallMethod("OnAfterDataRefreshed", new[] { new object(), EventArgs.Empty});

            // assert
            Assert.IsTrue(exportStartWasCalled);
            Assert.IsTrue(refreshSearchListWasCalled);

            Assert.AreEqual(25, privateAccessor.GetField("_pageSize"));
            Assert.AreEqual(10, privateAccessor.GetField("_currentPageNumber"));

            // arrange
            exportStartWasCalled = false;
            Mock.Arrange(() => vm.InfoListViewSource).ReturnsCollection(new Collection<IInfoClass>());

            // act
            privateAccessor.CallMethod("OnAfterDataRefreshed", new[] { new object(), EventArgs.Empty});

            // assert
            Assert.IsFalse(exportStartWasCalled);
        }
예제 #19
0
        public void GetFileCommand()
        {
            // arrange
            var vm = new FieldFileViewModel();

            var saveFileDialog = Mock.Create<SaveFileDialog>(Behavior.CallOriginal);
            Mock.Arrange(() => saveFileDialog.ShowDialog()).Returns(true);

            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_dialog", saveFileDialog);

            var fileProcess = Mock.Create<IFileProcess>(Behavior.Loose);
            fileProcess.OriginalFileName = "1.txt";
            fileProcess.FileName = "603512C1-87D1-48BA-9C3F-13DA0C9EF5C0.txt";
            Mock.NonPublic.Arrange<IFileProcess>(vm, "CurrentFileProcess").Returns(fileProcess);

            Mock.Arrange(() => vm.DialogFilter).Returns("File (*.txt)|*.txt");

            vm.DocHandlerUrl = "http://localhost:5558/";

            vm.CurrentState = FileControlMode.Upload;

            // act
            vm.GetFileCommand.Execute(null);

            // assert
            var dialog = (SaveFileDialog)privateAccessor.GetField("_dialog");

            Assert.AreEqual("File (*.txt)|*.txt", dialog.Filter);
            Assert.AreEqual("1.txt", dialog.DefaultFileName);

            Assert.AreEqual("Downloading ...", vm.DownloadPercent);
            Assert.AreEqual(FileControlMode.Download, vm.CurrentState);

            // arrange
            vm.DownloadPercent = null;
            Mock.Arrange(() => saveFileDialog.ShowDialog()).Returns(false);

            // act
            vm.GetFileCommand.Execute(null);

            // assert
            Assert.IsNull(vm.DownloadPercent);
        }
예제 #20
0
        public void ProcessRequest_ConvertedPDFDoesNotExist_RequestRedirected()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { "FileId", "1" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var dynamicTypeManager = Mock.Create<IDynamicTypeManager>(Behavior.CallOriginal);

            var fileProcess = Mock.Create<IFileProcess>(Behavior.Loose);
            fileProcess.FileName = "77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt.pdf";

            Mock.Arrange(() => dynamicTypeManager.GetEditableRoot<IFileProcess>(Constants.FileProcessName, 1)).
                Returns<string, int>((processName, id) => fileProcess);

            handler.TheDynamicTypeManager = dynamicTypeManager;

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt.pdf");

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);

            Mock.Arrange(() => response.ContentLength).Returns(0);
            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var called = false;
            Mock.Arrange(() => context.Response.Redirect("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt")).DoInstead(() => called = true);

            // act
            handler.ProcessRequest(context);

            // we don't redirect anymore
            //Assert.IsTrue(called);

            Assert.IsFalse(called);
        }
예제 #21
0
        public void Orientation()
        {
            // arrange
            var vm = new FieldFileViewModel();
            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_width", 308);

            // act
            var orientation = vm.Orientation;

            // assert
            Assert.IsTrue(orientation);

            // arrange
            privateAccessor.SetField("_width", 306);

            // act
            orientation = vm.Orientation;

            // assert
            Assert.IsFalse(orientation);
        }
예제 #22
0
        public void ProcessRequest_Main()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { Constants.FileProcessFileName, "77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt" },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt");

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);
            Mock.Arrange(() => response.ContentLength).Returns(1);

            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var responseWriteMethodWasCalled = false;
            Mock.Arrange(() => context.Response.Write("File not found. FileName = 77F3EB4C-5FF8-4D50-AC7C-A8E417A6AA3A.txt")).DoInstead(() => responseWriteMethodWasCalled = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(responseWriteMethodWasCalled);
            Assert.AreEqual("text/plain", context.Response.ContentType);

            // arrange
            var stream = Mock.Create<Stream>(Behavior.CallOriginal);

            var exit = false;
            Mock.Arrange(() => stream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
            {
                if (!exit)
                {
                    exit = true;
                    return Constants.FileProcessBufferSize;
                }

                return 0;
            });

            Mock.Arrange(() => response.GetResponseStream()).Returns(stream);

            var outputStreamWriteMethodWasCalled = false;
            Mock.Arrange(() => context.Response.OutputStream.Write(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).DoInstead(() => outputStreamWriteMethodWasCalled = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(outputStreamWriteMethodWasCalled);
        }
예제 #23
0
        public void UploadImageCommand()
        {
            // arrange
            var vm = new ImageFieldViewModel();

            var openFileDialog = Mock.Create<OpenFileDialog>(Behavior.CallOriginal);
            Mock.Arrange(() => openFileDialog.ShowDialog()).Returns(false);

            var privateAccessor = new PrivateAccessor(vm);
            privateAccessor.SetField("_openFileDialog", openFileDialog);

            try
            {
                // act
                vm.UploadImageCommand.Execute(null);
            }
            catch (Exception ex)
            {
                // assert
                Assert.Fail("Expected no exception, but got: " + ex.Message);
            }

            // arrange
            Mock.Arrange(() => openFileDialog.ShowDialog()).Returns(true);

            var file = Mock.Create<FileInfo>(Behavior.CallOriginal);
            Mock.Arrange(() => file.Length).Returns(8 * 1024);
            Mock.Arrange(() => openFileDialog.File).Returns(file);

            var popupFactory = new PopupFactory();
            var notifyFailureCalled = false;
            Mock.Arrange(() => popupFactory.NotifyFailure(Arg.AnyString, "Popup_Error", 3, false)).DoInstead(() => notifyFailureCalled = true);

            vm.ThePopupFactory = popupFactory;

            // act
            vm.UploadImageCommand.Execute(null);

            // assert
            Assert.IsTrue(notifyFailureCalled);

            // arrange
            Mock.NonPublic.Arrange<ulong>(vm, "MaxFileSize").Returns((ulong)file.Length + 1);

            var fileStream = Mock.Create<FileStream>(Behavior.Loose);

            var exit = false;
            Mock.Arrange(() => fileStream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
                    {
                        if (!exit)
                        {
                            exit = true;
                            return 1;
                        }

                        return 0;
                    });

            Mock.Arrange(() => file.OpenRead()).Returns(fileStream);

            var imageVisibilityRaises = false;
            Mock.NonPublic.Arrange(vm, "RaisePropertyChanged", ArgExpr.IsAny<Expression<Func<bool>>>()).DoInstead(() => imageVisibilityRaises = true);

            var downloadImageCommandRaises = false;
            Mock.Arrange(() => vm.DownloadImageCommand.RaiseCanExecuteChanged()).DoInstead(() => downloadImageCommandRaises = true);

            var clearImageCommandRaises = false;
            Mock.Arrange(() => vm.ClearImageCommand.RaiseCanExecuteChanged()).DoInstead(() => clearImageCommandRaises = true);

            // act
            vm.UploadImageCommand.Execute(null);

            // assert
            Assert.AreEqual(8 * 1024, ((byte[])vm.Value).Length);
            Assert.IsTrue(imageVisibilityRaises);
            Assert.IsTrue(downloadImageCommandRaises);
            Assert.IsTrue(clearImageCommandRaises);
            Assert.IsNull(privateAccessor.GetField("_openFileDialog"));
        }
예제 #24
0
        public void ProcessRequest_WhenUserUseIE()
        {
            // arrange
            Mock.SetupStatic(typeof(Ioc));
            var handler = new DocHandler();

            var context = Mock.Create<HttpContext>();

            var fileName = Guid.NewGuid() + ".mp4";

            Mock.Arrange(() => context.Request.QueryString).Returns(new NameValueCollection
                {
                    { Constants.FileProcessFileName, fileName },
                    { "BypassAuth", "true" } // necessary to run tests on the server
                });

            var privateAccessor = new PrivateAccessor(handler);
            privateAccessor.SetField("_fileProcessorUri", "http://localhost:5556/DocumentProcessor.ashx");

            var webRequest = WebRequest.Create("http://localhost:5556/DocumentProcessor.ashx?FileName=" + fileName);

            Mock.Arrange(() => WebRequest.Create(Arg.IsAny<Uri>())).Returns(webRequest);

            var response = Mock.Create<WebResponse>(Behavior.Loose);
            Mock.Arrange(() => response.ContentLength).Returns(1);

            Mock.Arrange(() => webRequest.GetResponse()).Returns(response);

            var stream = Mock.Create<Stream>(Behavior.CallOriginal);

            var exit = false;
            Mock.Arrange(() => stream.Read(Arg.IsAny<byte[]>(), 0, Arg.AnyInt)).Returns(() =>
            {
                if (!exit)
                {
                    exit = true;
                    return Constants.FileProcessBufferSize;
                }

                return 0;
            });

            Mock.Arrange(() => response.GetResponseStream()).Returns(stream);

            Mock.Arrange(() => context.Request.Browser.Browser).Returns("IE");

            privateAccessor.SetField("_tempDocumentUnc", Path.GetTempPath());

            Mock.Arrange(() => ConfigurationManager.AppSettings["ApplicationRootUrl"]).Returns("http://localhost:5558/");

            var redirectExecuted = false;

            var tmp = string.Format("http://localhost:5558/{0}/{1}", new DirectoryInfo(Path.GetTempPath()).Name, fileName);

            Mock.Arrange(() => context.Response.Redirect(tmp)).DoInstead(() => redirectExecuted = true);

            // act
            handler.ProcessRequest(context);

            // assert
            Assert.IsTrue(redirectExecuted);
        }
예제 #25
0
        public void Export()
        {
            // arrange
            var exportUtility = new ExportUtility();
            var privateAccessor = new PrivateAccessor(exportUtility);

            // act
            var result = (bool)privateAccessor.CallMethod("Export", new object[] { null, null });

            // assert
            Assert.IsFalse(result);

            // arrange
            var dialog = Mock.Create<SaveFileDialog>();
            privateAccessor.SetField("_saveFileDialog", dialog);

            // act
            result = (bool)privateAccessor.CallMethod("Export", new object[] { null, null });

            // assert
            Assert.IsFalse(result);

            // arrange
            var exportViewModel = new ExportOptionsViewModel();
            exportUtility.TheExportOptionsViewModel = new Lazy<ExportOptionsViewModel>(() => exportViewModel);

            var grid = new GridViewDataControl();

            using (var stream = new MemoryStream())
            {
                Mock.Arrange(() => dialog.OpenFile()).Returns(stream);

                // act
                result = (bool)privateAccessor.CallMethod("Export", new object[] { grid, "Id|CurrentState" });

                // assert
                Assert.IsTrue(result);
            }

            // arrange
            Mock.Arrange(() => grid.IsGrouping).Returns(true);
            Mock.Arrange(() => grid.Export(Arg.IsAny<Stream>(), Arg.IsAny<GridViewExportOptions>())).DoNothing();
            using (var stream = new MemoryStream())
            {
                Mock.Arrange(() => dialog.OpenFile()).Returns(stream);

                // act
                result = (bool)privateAccessor.CallMethod("Export", new object[] { grid, "Id|CurrentState" });

                // assert
                Assert.IsTrue(result);
            }

            // arrange
            using (var stream = new MemoryStream())
            {
                Mock.Arrange(() => dialog.OpenFile()).Returns(stream);
                exportViewModel.ExportFileType = ExportFileType.Pdf;

                // act
                result = (bool)privateAccessor.CallMethod("Export", new object[] { grid, null });

                // assert
                Assert.IsTrue(result);

                // arrange
                Mock.NonPublic.Arrange(exportUtility, "CreateDocument", grid).DoNothing();

                // act
                result = (bool)privateAccessor.CallMethod("Export", new object[] { grid, null });

                // assert
                Assert.IsFalse(result);
            }

            // arrange
            Mock.Arrange(() => grid.IsGrouping).Returns(false);
            using (var stream = new MemoryStream())
            {
                // arrange
                Mock.Arrange(() => dialog.OpenFile()).Returns(stream);
                Mock.NonPublic.Arrange(exportUtility, "CreateDocument", grid).CallOriginal();

                // act
                result = (bool)privateAccessor.CallMethod("Export", new object[] { grid, null });

                // assert
                Assert.IsTrue(result);
            }
        }
예제 #26
0
        public void WhenLocked_UserActionsShouldNotAffectInactivityTimer()
        {
            var vm = new MainViewModel();
            var timer = CreateTimer();
            var mainVmPrivateAccessor = new PrivateAccessor(vm);
            mainVmPrivateAccessor.SetField("_sessionInactivityTimer", timer);

            // Act
            mainVmPrivateAccessor.CallMethod("OnUserAction", new object[] { null, null });

            // Assert
            Assert.IsFalse(timer.IsEnabled);
        }
        public void OnAlternateStausChangedTest()
        {
            var container = new SpreadsheetItemContainer(null);
            var privateAccessor = new PrivateAccessor(container);

            //Prepare cells
            var childSpreadsheet = Mock.Create<SpreadsheetView>(Constructor.Mocked);
            var cell1 = Mock.Create<Cell>(Constructor.Mocked);            
            var cell2 = Mock.Create<StackCell>(Constructor.Mocked);
            Mock.Arrange(() => cell2.ChildSpreadsheet).Returns(childSpreadsheet);
            Mock.Arrange(() => cell2.HasNested).Returns(true);
            container.Cells.Add(cell1);
            container.Cells.Add(cell2);

            //Container is disposed
            Mock.Arrange(() => container.Cells).CallOriginal().OccursNever();
            privateAccessor.SetField("_disposed", true);
            container.IsAlternate = true;
            Mock.NonPublic.Assert(typeof(SpreadsheetItemContainer), "OnAlternateStausChanged", 
                Occurs.Once(), ArgExpr.IsAny<DependencyObject>(), ArgExpr.IsAny<DependencyPropertyChangedEventArgs>());
            Mock.Assert(() => childSpreadsheet.AlternateRows(), Occurs.Never());
            Mock.Assert(container);

            //Container is not disposed
            Mock.Arrange(() => container.Cells).CallOriginal().OccursOnce();
            privateAccessor.SetField("_disposed", false);
            container.IsAlternate = false;
            Mock.NonPublic.Assert(typeof(SpreadsheetItemContainer), "OnAlternateStausChanged",
                Occurs.Exactly(2), ArgExpr.IsAny<DependencyObject>(), ArgExpr.IsAny<DependencyPropertyChangedEventArgs>());
            Mock.Assert(() => childSpreadsheet.AlternateRows(), Occurs.Once());
            Mock.Assert(container);
            Assert.IsTrue(cell2.HasNested);
        }
예제 #28
0
        public void OnUserActions_InactivityCountDownShouldBeReseted()
        {
            var timer = CreateTimer(true);
            Mock.Arrange(() => timer.Restart());

            var mainVmPrivateAccessor = new PrivateAccessor(new MainViewModel());
            mainVmPrivateAccessor.SetField("_sessionInactivityTimer", timer);

            // Act
            mainVmPrivateAccessor.CallMethod("OnUserAction", new object[] { null, null });

            // Assert
            Assert.IsTrue(timer.IsEnabled);
            Mock.Assert(() => timer.Restart(), Occurs.Once());
        }
예제 #29
0
        public void OnItemsChangedItemAddTest()
        {
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);

            //Initialize ItemCollection
            Mock.NonPublic.Arrange(spreadsheet, "OnItemsChanged", ArgExpr.IsAny<NotifyCollectionChangedEventArgs>()).DoNothing();
            spreadsheet.ItemsSource = new List<TestData>();
            spreadsheet.OnApplyTemplate();
            Assert.IsNotNull(spreadsheet.ItemsCollection);
            Mock.Reset();

            //Create data item and its wrapper
            var dataItem = new TestData {Text = "test", FractionalNumber = 3.5};
            var itemWrap = ItemWrap.BuildNew(dataItem);

            //Arrabge ManageExpandStates and BindContainerToItem
            Mock.Arrange(() => spreadsheet.ManageExpandStates(Arg.IsAny<IDetailColumn>()));
            Mock.NonPublic.Arrange(spreadsheet, "BindContainerToItem", ArgExpr.IsAny<SpreadsheetItemContainer>(), ArgExpr.IsAny<IWrap>());

            //Make spreadsheet disposed
            privateAccessor.SetField("_disposed", true);
            spreadsheet.ItemsCollection.Add(itemWrap);

            //Check ManageExpandStates and BindContainerToItem invocations when spreadsheet is disposed
            Assert.IsTrue((bool)privateAccessor.GetField("_disposed"));
            Mock.NonPublic.Assert(spreadsheet, "BindContainerToItem", Occurs.Never(), ArgExpr.IsAny<SpreadsheetItemContainer>(), ArgExpr.IsAny<IWrap>());
            Mock.Assert(() => spreadsheet.ManageExpandStates(Arg.IsAny<IDetailColumn>()), Occurs.Never());

            //Mock ItemContainerGenerator.ContainerFromItem method and add new item to ItemsCollection
            //this invokes OnItemsChanged
            privateAccessor.SetField("_disposed", false);
            var container = new SpreadsheetItemContainer(spreadsheet);
            Mock.Arrange(() => spreadsheet.ItemContainerGenerator.ContainerFromItem(Arg.IsAny<object>())).Returns(container);
            Mock.Arrange(() => spreadsheet.ParentColumn).Returns(Mock.Create<IDetailColumn>());
            spreadsheet.ItemsCollection.Add(itemWrap);

            //Check ManageExpandStates and BindContainerToItem invocations when spreadsheet is not disposed
            Assert.IsFalse((bool)privateAccessor.GetField("_disposed"));
            Mock.NonPublic.Assert(spreadsheet, "BindContainerToItem", Occurs.Once(), container, itemWrap);
            Mock.Assert(() => spreadsheet.ManageExpandStates(Arg.IsAny<IDetailColumn>()), Occurs.Once());
        }
예제 #30
0
        private static DispatcherTimer CreateTimer(MainViewModel viewModel, bool enableTimer = false)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }

            var timer = CreateTimer(enableTimer);

            var vmPrivateAccessor = new PrivateAccessor(viewModel);
            vmPrivateAccessor.SetField("_sessionInactivityTimer", timer);

            return timer;
        }