runceel / ReactiveProperty

ReactiveProperty provides MVVM and asynchronous support features under Reactive Extensions. Target frameworks are .NET 6+, .NET Framework 4.7.2 and .NET Standard 2.0.
MIT License
903 stars 101 forks source link

Is Unit Testing ReactiveProperties Possible? #212

Closed kgc00 closed 3 years ago

kgc00 commented 4 years ago

Hi,

Is it possible to Unit Test reactive properties? I've got a simple sandbox with:

    public class ReactiveThing {
        public ReactiveProperty<int> rpInt { get; private set; }
        public SomeModel Model;
        public ReactiveThing() {
            Model = new SomeModel();
            rpInt = ReactiveProperty.FromObject(Model, x => x.someInt);
        }
    }
    public class SomeModel {
        public int someInt { get; set; }
        public void Update() => someInt += 1;
    }
        [Test]
        public void Board_Has_Observable() {
            var rt = new ReactiveThing();

            rt.Model.Update();
            rt.Model.Update();

            rt.rpInt.Value.ShouldBe(2);
        }

But my test fails with:

Shouldly.ShouldAssertException : rt.copyOfObservale.Value
    should be
2
    but was
0

Do tests need to be structured in some kind of way to facilitate reactive proprty updates?

runceel commented 4 years ago

@kgc00 FromObject method works as 'one way to source binding'. In this case, the source is SomeModel class, the target is the Reactiveproperty instance.

If you want to sync between SomeModel and ReactiveProperty, then you have to implement INotifyPropertyChanged interface to SomeModel, and then change ReactiveThing class like below:

    public class ReactiveThing {
        public ReactiveProperty<int> rpInt { get; private set; }
        public SomeModel Model;
        public ReactiveThing() {
            Model = new SomeModel();
            // ObserveProperty is defined as an extension method of INotifyPropertyChanged interface
            rpInt = Model.ObserveProperty(x => x.someInt).ToReactiveProperty();
        }
    }
runceel commented 4 years ago

@kgc00 I have created a sample project. Please check the following link: https://github.com/runceel/Issue212/blob/master/Issue212/UnitTest1.cs

kgc00 commented 3 years ago

Hi @runceel,

I see now what I was doing wrong. Thanks for the help!

runceel commented 3 years ago

@kgc00 No problem.