Ejemplo n.º 1
0
        public void AsyncValidation_SyncRule_ExecutedAsyncroniously()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) =>
            {
                var vm = new DummyViewModel();
                vm.Foo = null;

                var validation = new ValidationHelper();

                validation.AddRule(() =>
                {
                    Assert.False(dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId,
                                 "Rule must be executed in a background thread.");

                    if (string.IsNullOrEmpty(vm.Foo))
                    {
                        return(RuleResult.Invalid("Foo cannot be empty string."));
                    }

                    return(RuleResult.Valid());
                });

                validation.ValidateAllAsync().ContinueWith(r => completedAction());
            });
        }
Ejemplo n.º 2
0
        public void RemoveAllRules_HadTwoNegativeRulesRegisteredForDifferentTargets_ResultChangedIsFiredForAllTargets()
        {
            // ARRANGE
            var dummy = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(() => dummy.Foo, () => RuleResult.Invalid("error1"));
            validation.AddRule(() => dummy.Bar, () => RuleResult.Invalid("error2"));

            validation.ValidateAll();

            int resultChangedFiredCount = 0;

            validation.ResultChanged += (sender, args) =>
            {
                resultChangedFiredCount++;
            };

            // ACT
            validation.RemoveAllRules();

            // VERIFY
            Assert.Equal(2, resultChangedFiredCount);
        }
Ejemplo n.º 3
0
        public void GetViewTest()
        {
            IView          view      = new ViewMock();
            DummyViewModel viewModel = new DummyViewModel(view);

            Assert.AreEqual(view, viewModel.View);
        }
Ejemplo n.º 4
0
        public void DoesNotLeakMemory()
        {
            var vm = new DummyViewModel {
                NullableDoubleValue = null
            };
            var textBox = new TextBox {
                DataContext = vm
            };

            textBox.SetCulture(new CultureInfo("en-US"));
            textBox.SetDecimalDigits(2);

            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                Mode = BindingMode.TwoWay
            };

            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);

            var wr = new WeakReference(textBox);

            textBox = null;
            GC.Collect();
            Assert.IsFalse(wr.IsAlive);
        }
Ejemplo n.º 5
0
        public void UpdatesWhenCultureChanges()
        {
            var vm = new DummyViewModel {
                NullableDoubleValue = 3
            };
            var textBox = new TextBox {
                DataContext = vm
            };
            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                Mode = BindingMode.TwoWay
            };

            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);
            textBox.RaiseLoadedEvent();

            textBox.SetCulture(new CultureInfo("en-US"));

            textBox.WriteText("1,2", true);
            AssertError <CanParseError>(textBox);
            Assert.AreEqual(3, textBox.GetValue(Input.ValueProperty));
            Assert.AreEqual(3, vm.NullableDoubleValue);

            textBox.SetCulture(new CultureInfo("sv-SE"));
            AssertNoError(textBox);
            Assert.AreEqual(1.2, textBox.GetValue(Input.ValueProperty));
            Assert.AreEqual(1.2, vm.NullableDoubleValue);
        }
Ejemplo n.º 6
0
        public void ValidatedAsync_AsyncRuleDoesnotCallCallback_ThrowsAnExceptionAfterTimeout()
        {
            TestUtils.ExecuteWithDispatcher((uiThreadDispatcher, completedAction) =>
            {
                // ARRANGE
                var validation = new ValidationHelper();
                validation.AsyncRuleExecutionTimeout = TimeSpan.FromSeconds(0.1);

                var dummy = new DummyViewModel();

                validation.AddAsyncRule(() => dummy.Foo,
                                        onCompleted =>
                {
                    // Do nothing
                });

                // ACT
                var ui = TaskScheduler.FromCurrentSynchronizationContext();

                validation.ValidateAllAsync().ContinueWith(result =>
                {
                    Assert.True(result.IsFaulted, "Validation task must fail.");
                    Assert.NotNull(result.Exception);

                    completedAction();
                }, ui);
            });
        }
Ejemplo n.º 7
0
        public void ValidateAsync_WithCallback_ValidationOccuredAndCallbackIsCalledOnUIThread()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) =>
            {
                var vm            = new DummyViewModel();
                vm.Foo            = null;
                bool ruleExecuted = false;

                var validation = new ValidationHelper();

                validation.AddAsyncRule(setResult =>
                {
                    ruleExecuted = true;
                    setResult(RuleResult.Invalid("Error1"));
                });

                validation.ValidateAllAsync(result =>
                {
                    Assert.True(ruleExecuted, "Validation rule must be executed before validation callback is called.");
                    Assert.Equal(dispatcher.Thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);

                    completedAction();
                });
            });
        }
Ejemplo n.º 8
0
        public void GetViewTest()
        {
            IView view = new ViewMock();
            DummyViewModel viewModel = new DummyViewModel(view);

            Assert.AreEqual(view, viewModel.View);
        }
Ejemplo n.º 9
0
        public void UpdatesOnCultureChange()
        {
            var vm = new DummyViewModel {
                NullableDoubleValue = null
            };
            int count = 0;

            vm.PropertyChanged += (_, __) => count++;
            var textBox = new TextBox {
                DataContext = vm
            };

            textBox.SetCulture(new CultureInfo("en-US"));
            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Mode = BindingMode.TwoWay
            };

            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);
            textBox.RaiseLoadedEvent();

            Assert.IsNullOrEmpty(textBox.GetRawText());
            Assert.AreEqual(null, textBox.GetRawValue());

            textBox.WriteText("1.234");
            Assert.AreEqual(1, count);
            Assert.AreEqual("1.234", textBox.Text);

            textBox.SetCulture(new CultureInfo("sv-SE"));
            Assert.AreEqual(1, count);
            Assert.AreEqual("1,234", textBox.Text);
        }
Ejemplo n.º 10
0
        public void AsyncValidation_DependantProperties_IfOneInvalidSecondIsInvalidToo()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, testCompleted) =>
            {
                var vm = new DummyViewModel
                {
                    Foo = "abc",
                    Bar = "abc"
                };

                Func <bool> validCondition = () => vm.Foo != vm.Bar;

                var validation = new ValidationHelper();

                validation.AddAsyncRule(
                    () => vm.Foo,
                    () => vm.Bar,
                    setResult =>
                {
                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        setResult(RuleResult.Assert(validCondition(), "Foo must be different than bar"));
                    });
                });

                validation.ValidateAsync(() => vm.Bar).ContinueWith(r =>
                {
                    Assert.False(r.Result.IsValid, "Validation must fail");
                    Assert.True(r.Result.ErrorList.Count == 2, "There must be 2 errors: one for each dependant property");

                    testCompleted();
                });
            });
        }
Ejemplo n.º 11
0
        public void ResultChanged_ValidateExecutedForSeveralRules_FiresForEachTarget()
        {
            // Arrange
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            validation.AddRule(nameof(dummy.Foo),
                               () => RuleResult.Invalid("Error"));
            validation.AddRule(nameof(dummy.Foo),
                               RuleResult.Valid);
            validation.AddRule(nameof(dummy.Bar),
                               RuleResult.Valid);
            validation.AddRule(() => RuleResult.Invalid("Error"));

            const int expectedTimesToFire = 0 + 1 /*Invalid Foo*/ + 1 /* Invalid general target */;
            var       eventFiredTimes     = 0;

            validation.ResultChanged += (o, e) => { eventFiredTimes++; };

            // Act
            validation.ValidateAll();

            // Verify
            Assert.Equal(expectedTimesToFire, eventFiredTimes);
        }
Ejemplo n.º 12
0
        public void ResetsOnDataContext()
        {
            var textBox = new TextBox();

            textBox.SetCulture(new CultureInfo("en-US"));
            textBox.SetDecimalDigits(2);

            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                Mode = BindingMode.TwoWay
            };

            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);

            Assert.Inconclusive("What is most right here? Maybe propagating the value from vm -> view");
            textBox.WriteText("1.234");
            Assert.AreEqual("1.234", textBox.GetRawText());
            Assert.AreEqual(RawValueTracker.Unset, textBox.GetRawValue());
            Assert.AreEqual(RawValueSource.User, textBox.GetRawValueSource());

            var vm = new DummyViewModel {
                NullableDoubleValue = null
            };

            textBox.DataContext = vm;
            Assert.AreEqual("1.234", textBox.GetRawText());
            Assert.AreEqual(1.234, textBox.GetRawValue());
            Assert.AreEqual(RawValueSource.User, textBox.GetRawValueSource());
        }
Ejemplo n.º 13
0
        public void Validate_MultipleRulesForSameTarget_ClearsResultsBeforeValidation()
        {
            // ARRANGE
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            RuleResult firstRuleResult  = RuleResult.Valid();
            RuleResult secondRuleResult = RuleResult.Invalid("Error2");

            validation.AddRule(nameof(dummy.Foo),
                               () => { return(firstRuleResult); });
            validation.AddRule(nameof(dummy.Foo),
                               () => { return(secondRuleResult); });

            // ACT

            validation.ValidateAll();

            firstRuleResult = RuleResult.Invalid("Error1");

            validation.ValidateAll();

            // VERIFY

            var result = validation.GetResult(nameof(dummy.Foo));

            Assert.False(result.IsValid);
            Assert.Equal(1, result.ErrorList.Count);
            Assert.Equal("Error1", result.ErrorList[0].ErrorText);
        }
Ejemplo n.º 14
0
        public void Validate_MultipleRulesForSameTarget_DoesNotExecuteRulesIfPerviousFailed()
        {
            // ARRANGE
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            bool firstRuleExecuted  = false;
            bool secondRuleExecuted = false;

            validation.AddRule(nameof(dummy.Foo),
                               () =>
            {
                firstRuleExecuted = true;
                return(RuleResult.Invalid("Error1"));
            });
            validation.AddRule(nameof(dummy.Foo),
                               () =>
            {
                secondRuleExecuted = true;
                return(RuleResult.Invalid("Error2"));
            });

            // ACT

            validation.ValidateAll();

            // VERIFY

            Assert.True(firstRuleExecuted, "First rule must have been executed");
            Assert.False(secondRuleExecuted, "Second rule should not have been executed because first rule failed.");
        }
Ejemplo n.º 15
0
        public void RemoveRule_ThereAreTwoFailedRules_RemoveOne_ResultChangedShouldBeFiredWithNewResultStillInvalid()
        {
            // ARRANGE
            var dummy = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(nameof(dummy.Foo), () => RuleResult.Invalid("error2"));
            var invalidRule = validation.AddRule(nameof(dummy.Foo), () => RuleResult.Invalid("error"));

            var validationResult = validation.ValidateAll();

            Assert.False(validationResult.IsValid);

            bool resultChangedEventFired = false;

            validation.ResultChanged += (sender, args) =>
            {
                Assert.Equal(nameof(dummy.Foo), args.Target);
                Assert.False(args.NewResult.IsValid);

                resultChangedEventFired = true;
            };

            // ACT
            validation.RemoveRule(invalidRule);

            // VERIFY
            Assert.True(resultChangedEventFired);
        }
Ejemplo n.º 16
0
        public void UpdatesWhenVmChanges()
        {
            var vm = new DummyViewModel {
                NullableDoubleValue = null
            };
            var textBox = new TextBox {
                DataContext = vm
            };

            textBox.SetCulture(new CultureInfo("en-US"));
            textBox.SetDecimalDigits(2);
            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                Mode = BindingMode.TwoWay
            };

            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);
            textBox.RaiseLoadedEvent();
            Assert.IsNullOrEmpty(textBox.GetRawText());
            Assert.AreEqual(null, textBox.GetRawValue());

            vm.NullableDoubleValue = 1.23456;

            Assert.AreEqual("1.23456", textBox.GetRawText());
            Assert.AreEqual(1.23456, textBox.GetRawValue());
            Assert.AreEqual(RawValueSource.Binding, textBox.GetRawValueSource());
        }
Ejemplo n.º 17
0
        public void UpdatesOnUserErrorInput()
        {
            var vm = new DummyViewModel {
                NullableDoubleValue = null
            };
            var textBox = new TextBox {
                DataContext = vm
            };

            textBox.SetCulture(new CultureInfo("en-US"));
            textBox.SetDecimalDigits(2);

            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                Mode = BindingMode.TwoWay
            };

            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);
            textBox.RaiseLoadedEvent();

            Assert.IsNullOrEmpty(textBox.GetRawText());
            Assert.AreEqual(null, textBox.GetRawValue());

            textBox.WriteText("1.2dae");

            Assert.AreEqual("1.2dae", textBox.GetRawText());
            Assert.AreEqual(RawValueTracker.Unset, textBox.GetRawValue());
            Assert.AreEqual(RawValueSource.User, textBox.GetRawValueSource());
        }
Ejemplo n.º 18
0
        public void PropertyLambaMustNotBeAMethodCall()
        {
            var dummyControl   = new DummyControl();
            var dummyViewModel = new DummyViewModel();
            var ex             = Record.Exception(() => dummyControl.Bind(_ => _.ToString(), dummyViewModel, _ => _.ToString()));

            Assert.NotNull(ex);
            Assert.Equal(string.Format(Extensions.EXPRESSION_REFERS_METHOD, "_ => _.ToString()"), ex.Message);
        }
Ejemplo n.º 19
0
        /// <summary>A helper method that acts as a receiver for events.</summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Information regarding the event.</param>
        private void ReceivePropertyChangedEvent(object sender, PropertyChangedEventArgs e)
        {
            DummyViewModel testSubject = sender as DummyViewModel;

            if (testSubject != null)
            {
                testSubject.IsHandledByEvent = true;
            }
        }
Ejemplo n.º 20
0
        public void PropertyLambaMustNotBeAField()
        {
            var dummyControl   = new DummyControl();
            var dummyViewModel = new DummyViewModel();
            var ex             = Record.Exception(() => dummyControl.Bind(_ => _.DummyString, dummyViewModel, _ => _._DummyString));

            Assert.NotNull(ex);
            Assert.Equal(string.Format(Extensions.EXPRESSION_REFERS_FIELD, "_ => _.DummyString"), ex.Message);
        }
Ejemplo n.º 21
0
 public void SetUp()
 {
     _vm        = new DummyViewModel();
     _doubleBox = CreateTextBox("DoubleValue");
     _intBox    = CreateTextBox("IntValue");
     _grid      = new Grid();
     _grid.Children.Add(_doubleBox);
     _grid.Children.Add(_intBox);
     _grid.SetIsValidationScope(true);
 }
Ejemplo n.º 22
0
        public void AsyncValidation_ExecutedInsideUIThreadTask_ValidationRunsInBackgroundThread()
        {
            // This test checks the situation described here:
            // http://stackoverflow.com/questions/6800705/why-is-taskscheduler-current-the-default-taskscheduler
            // In short: if a continuation of a task runs on the UI thread, then the tasks that you start using
            // Task.Factory.StartNew will run also on the UI thread. This is unexpected an may cause a deadlock, or freezing UI.

            TestUtils.ExecuteWithDispatcher((uiThreadDispatcher, completedAction) =>
            {
                // ARRANGE
                var validation = new ValidationHelper();

                var dummy = new DummyViewModel();

                int uiThreadId         = Thread.CurrentThread.ManagedThreadId;
                int validationThreadId = uiThreadId;

                validation.AddAsyncRule(nameof(dummy.Foo),
                                        () =>
                {
                    return(Task.Run(() =>
                    {
                        validationThreadId = Thread.CurrentThread.ManagedThreadId;

                        return RuleResult.Valid();
                    }));
                });

                // ACT

                // Execute validation within a continuation of another task that runs on
                // current synchronization context, so that the TaskScheduler.Current is set to the
                // UI context.
                Task.Factory.StartNew(() => { }).ContinueWith(t =>
                {
                    Task <ValidationResult> task = validation.ValidateAllAsync();

                    task.ContinueWith(result =>
                    {
                        // VERIFY

                        // Schedule the varification code with the dispatcher in order to take it
                        // out of the ContinueWith continuation. Otherwise the exceptions will be stored inside the task and
                        // unit testing framework will not know about them.
                        uiThreadDispatcher.BeginInvoke(new Action(() =>
                        {
                            Assert.False(uiThreadId == validationThreadId,
                                         "Validation must be executed in a background thread, so that the UI thread is not blocked.");

                            completedAction();
                        }));
                    });
                }, TaskScheduler.FromCurrentSynchronizationContext());
            });
        }
Ejemplo n.º 23
0
        public void AsyncValidation_GeneralSmokeTest()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) =>
            {
                var vm = new DummyViewModel {
                    Foo = null
                };

                var validation = new ValidationHelper();

                bool ruleExecuted = false;

                // OK, this is really strange, but if Action<bool> is not mentioned anywhere in the project, then ReSharter would fail to build and run the test...
                // So including the following line to fix it.
                Action <RuleResult> dummy = null;
                Assert.Null(dummy); // Getting rid of the "unused variable" warning.

                validation.AddAsyncRule(async() =>
                {
                    return(await Task.Run(() =>
                    {
                        ruleExecuted = true;

                        return RuleResult.Invalid("Foo cannot be empty string.");
                    }));
                });

                validation.ResultChanged += (o, e) =>
                {
                    Assert.True(ruleExecuted,
                                "Validation rule must be executed before ValidationCompleted event is fired.");

                    var isUiThread = dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId;

                    Assert.True(isUiThread, "ValidationResultChanged must be executed on UI thread");
                };

                var ui = TaskScheduler.FromCurrentSynchronizationContext();

                validation.ValidateAllAsync().ContinueWith(r =>
                {
                    var isUiThread = dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId;

                    Assert.True(isUiThread, "Validation callback must be executed on UI thread");

                    Assert.False(r.Result.IsValid, "Validation must fail according to the validaton rule");
                    Assert.False(validation.GetResult().IsValid, "Validation must fail according to the validaton rule");

                    Assert.True(ruleExecuted, "Rule must be executed before validation completed callback is executed.");

                    completedAction();
                }, ui);
            });
        }
Ejemplo n.º 24
0
        public void SampleSite_DummyTest1()
        {
            // Arrange
            var model        = new DummyViewModel();
            var firstNumber  = 10;
            var secondNumber = 20;
            // Act
            var result = model.Add(firstNumber, secondNumber);

            // Assert
            Assert.Equal(30, result);
        }
Ejemplo n.º 25
0
        /// <summary>A helper method that acts as a receiver for messages.</summary>
        /// <param name="message">The received message.</param>
        private void ReceivePropertyChangedMessage(PropertyChangedMessage <int> message)
        {
            DummyViewModel testSubject = message.Sender as DummyViewModel;

            if (testSubject != null)
            {
                if (message.PropertyName == "IntegerValue" && message.OldValue == testSubject.OriginalIntegerValue && message.NewValue == testSubject.IntegerValue)
                {
                    testSubject.IsHandledByMessage = true;
                }
            }
        }
Ejemplo n.º 26
0
 // if we use the same action name  as Get action does, then
 // .RedirectToAction() will incorrectly make the link to Post(!) method
 // the issue occurs for the route patterns such as [controller]/{tenantId}/action_name
 public IActionResult Same(DummyViewModel vm)
 {
     try
     {
         return(Content($"Hello, this is HttpPost action"));
     }
     catch (Exception ex)
     {
         _logger.LogError(ex.Message);
         return(Content($"Error : {ex.Message}"));
     }
 }
Ejemplo n.º 27
0
        public void AsyncValidation_SeveralAsyncRules_AllExecutedBeforeValidationCompleted()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) =>
            {
                var vm = new DummyViewModel();
                vm.Foo = null;

                var validation = new ValidationHelper();

                bool rule1Executed = false;

                validation.AddAsyncRule(() =>
                {
                    return(Task.Run(() =>
                    {
                        rule1Executed = true;
                        return RuleResult.Valid();
                    }));
                });

                bool rule2Executed = false;

                validation.AddAsyncRule(() =>
                {
                    return(Task.Run(() =>
                    {
                        rule2Executed = true;
                        return RuleResult.Valid();
                    }));
                });

                bool rule3Executed = false;

                validation.AddAsyncRule(() =>
                {
                    return(Task.Run(() =>
                    {
                        rule3Executed = true;
                        return RuleResult.Valid();
                    }));
                });

                validation.ValidateAllAsync().ContinueWith(r =>
                {
                    Assert.True(rule1Executed);
                    Assert.True(rule2Executed);
                    Assert.True(rule3Executed);
                    Assert.True(r.Result.IsValid);

                    completedAction();
                });
            });
        }
Ejemplo n.º 28
0
        public void ResultChanged_RuleErrorsChangedButRuleValidityDidNotChange_EventStillFires()
        {
            // ARRANGE
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            validation.AddRule(() => dummy.Foo,
                               () =>
            {
                if (string.IsNullOrEmpty(dummy.Foo))
                {
                    return(RuleResult.Invalid("Foo should not be empty"));
                }

                return
                (RuleResult.Assert(dummy.Foo.Length > 5, "Length must be greater than 5").Combine(
                     RuleResult.Assert(dummy.Foo.Any(Char.IsDigit), "Must contain digit")));
            });

            var       resultChangedCalledTimes   = 0;
            const int expectedResultChangedCalls = 1 /* First invalid value */ + 1 /* Second invalid value */ + 1 /* Third invalid value */ + 1 /* Valid value */;

            validation.ResultChanged += (o, e) =>
            {
                resultChangedCalledTimes++;
            };

            // ACT

            dummy.Foo = null;

            // Should generage "Foo should not be empty" error
            validation.ValidateAll();

            dummy.Foo = "123";

            // Should generate the "Length must be greater than 5" error
            validation.ValidateAll();

            dummy.Foo = "sdfldlssd";

            // Should generate the "Must contain digit" error
            validation.ValidateAll();

            dummy.Foo = "lsdklfjsld2342";

            // Now should be valid
            validation.ValidateAll();

            // VERIFY
            Assert.Equal(expectedResultChangedCalls, resultChangedCalledTimes);
        }
 public static Pageable <DummyViewModel> ToPageableDummyViewModel(IEnumerable <DummyModel> src, Pageable <DummyViewModel> dest)
 {
     if (src != null)
     {
         foreach (var s in src)
         {
             var dummyViewModel = new DummyViewModel();
             Map(s, dummyViewModel);
             dest.Add(dummyViewModel);
         }
     }
     return(dest);
 }
Ejemplo n.º 30
0
        public void ViewModel_PropertyChanged()
        {
            /* First, create an instance of the viewmodel */
            DummyViewModel testSubject = new DummyViewModel();

            /* Set some properties and fixate the test subject */
            testSubject.BooleanValue = true;
            testSubject.IntegerValue = 42;
            testSubject.Fixate();

            /* Register handlers */
            testSubject.PropertyChanged += this.ReceivePropertyChangedEvent;
            testSubject.Messenger.Register <PropertyChangedMessage <bool> >(this, this.ReceivePropertyChangedMessage);
            testSubject.Messenger.Register <PropertyChangedMessage <int> >(this, this.ReceivePropertyChangedMessage);

            /* Change the first property */
            testSubject.BooleanValue = false;

            /* Allow for the messenger to process the send-request and the registered action to complete */
            int roundtrips = 0;

            while (roundtrips < 5 && !testSubject.IsHandledByEvent && !testSubject.IsHandledByMessage)
            {
                ++roundtrips;
                Thread.Yield();
            }

            /* Check if any events or messages where received */
            Assert.IsTrue(testSubject.IsHandledByEvent);
            Assert.IsTrue(testSubject.IsHandledByMessage);

            /* Reset the handled-flags */
            testSubject.IsHandledByEvent   = false;
            testSubject.IsHandledByMessage = false;

            /* Change the second property */
            testSubject.IntegerValue = 88;

            /* Allow for the messenger to process the send-request and the registered action to complete */
            roundtrips = 0;
            while (roundtrips < 5 && !testSubject.IsHandledByEvent && !testSubject.IsHandledByMessage)
            {
                ++roundtrips;
                Thread.Yield();
            }

            /* Check if any events or messages where received */
            Assert.IsTrue(testSubject.IsHandledByEvent);
            Assert.IsFalse(testSubject.IsHandledByMessage);
        }
Ejemplo n.º 31
0
        public static void Map(DummyModel source, DummyViewModel target)
        {
            target.DummyID      = source.DummyID;
            target.Name         = source.Name;
            target.Description  = source.Description;
            target.Date         = source.Date;
            target.Time         = source.Time;
            target.Currency     = source.Currency;
            target.EmailAddress = source.EmailAddress;
            target.Url          = source.Url;
            target.Decimal1     = source.Decimal1;

            target.DateTime = source.DateTime ?? DateTime.MinValue;
        }
Ejemplo n.º 32
0
        public void Handling_main_request_with_main_NOT_already_active_should_work_but_not_create_a_new_instance()
        {
            /* Arrange */
            var mocks = new TestAssistant().MockAll();
            var main = A.Dummy<MainViewModel>();
            var active = new DummyViewModel();

            var vm = new ShellViewModel(main, mocks.Messenger, mocks.ViewModelFactory);
            var handler = vm as IHandle<ViewRequest>;

            vm.ActiveItem = active;
            vm.MonitorEvents();

            /* Act */
            handler.Handle(ViewRequest.MainView);

            /* Assert */
            A.CallTo(() => mocks.ViewModelFactory.Get(typeof(DummyViewModel))).MustNotHaveHappened();
            vm.ActiveItem.Should().BeSameAs(main);
            vm.ShouldRaisePropertyChangeFor((svm) => svm.ActiveItem);
        }
Ejemplo n.º 33
0
 public void Setup()
 {
     model = RandomData.GetViewModel();
     this.provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());
     ModelValidatorProviders.Providers.Add(this.provider);
     DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
     var viewData = new ViewDataDictionary<DummyViewModel>(model);
     var mockHttpContext = HttpMocks.GetHttpContextMock();
     var controllerContext = new Mock<ControllerContext>(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
     var mockViewContext = new Mock<ViewContext>(
         controllerContext.Object,
         new Mock<IView>().Object,
         viewData,
         new TempDataDictionary(),
         TextWriter.Null);
     mockViewContext.SetupGet(c => c.ViewData).Returns(viewData);
     mockViewContext.SetupGet(c => c.HttpContext).Returns(mockHttpContext.Object);
     var mockViewDataContainer = new Mock<BaseView<DummyViewModel>>();
     mockViewDataContainer.Object.SetViewData(viewData);
     mockViewDataContainer.Setup(v => v.WebElementTranslations).Returns(new WebElementLocalizer(null));
     this.htmlHelper = new HtmlHelper<DummyViewModel>(mockViewContext.Object, mockViewDataContainer.Object);
 }
Ejemplo n.º 34
0
        public void DropDownForNullValueHtmlAttributestStillCreatesMarkup()
        {
            DummyViewModel model = new DummyViewModel { SelectListItemListProperty = RandomData.GetSelectListItemDictionary() };

            var res = this.htmlHelper.UmaDropDownFor(o => o.StringProperty, model.SelectListItemListProperty).ToString();

            //resulet example
            //<select class="selectpicker" id="StringProperty" name="StringProperty"><option value="">N:ņęįnпdāē</option>
            res.Should().NotBeNullOrEmpty();
        }
Ejemplo n.º 35
0
 public void InitTestFieldValues()
 {
     model = RandomData.GetViewModel();
     var viewData = new ViewDataDictionary<DummyViewModel>(model);
     var mockHttpContext = HttpMocks.GetHttpContextMock();
     var controllerContext = new Mock<ControllerContext>(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
     var mockViewContext = new Mock<ViewContext>(
         controllerContext.Object,
         new Mock<IView>().Object,
         viewData,
         new TempDataDictionary(),
         TextWriter.Null);
     mockViewContext.SetupGet(c => c.ViewData).Returns(viewData);
     mockViewContext.SetupGet(c => c.HttpContext).Returns(mockHttpContext.Object);
     var mockViewDataContainer = new Mock<BaseView<DummyViewModel>>();
     mockViewDataContainer.Object.SetViewData(viewData);
     mockViewDataContainer.Setup(v => v.WebElementTranslations).Returns(new WebElementLocalizer(null));
     this.htmlHelper = new HtmlHelper<DummyViewModel>(mockViewContext.Object, mockViewDataContainer.Object);
     this.localizer = new WebElementLocalizer(null);
 }
Ejemplo n.º 36
0
        public void DropDownForEmptyListThrowsException()
        {
            DummyViewModel model = new DummyViewModel { SelectListItemListProperty = new Dictionary<string, string>() };

            this.htmlHelper.UmaDropDownFor(o => o.StringProperty, model.SelectListItemListProperty, null);
        }
Ejemplo n.º 37
0
        public void SetUp()
        {
            _stubDummyRepository = MockRepository.GenerateStub<IDummyRepository>();
            _stubMessageBoxService = MockRepository.GenerateStub<IMessageBoxService>();
            _containerFacade = MockRepository.GenerateStub<IContainerFacade>();

            _containerFacade.Stub(x => x.Resolve<DummyBrowserViewModel>()).Return(
                new DummyBrowserViewModel(_stubDummyRepository));
            _containerFacade.Stub(x => x.Resolve<DummyDetailViewModel>()).Return(
                new DummyDetailViewModel());
            //EntityBrowserViewModel = (TBrowser) Activator.CreateInstance(typeof (TBrowser), entityRepository);
            //EntityBrowserViewModel = ContainerFacade.Resolve<TBrowser>();
            ////EntityDetailViewModel = (TDetail) Activator.CreateInstance(typeof (TDetail));
            //EntityDetailViewModel = ContainerFacade.Resolve<TDetail>();

            _dummyViewModel = new DummyViewModel(_stubDummyRepository, _stubMessageBoxService, _containerFacade);
            Assert.AreEqual(ViewMode.BrowseMode, _dummyViewModel.CurrentViewMode);
        }