我尝试创建一个继承自 ReactiveObject 的基类。 此类需要检查任何属性(包括进一步继承的属性)是否已更改。
我的主要问题是,我得不到任何可靠的测试结果! 提供的测试可能是绿色的。使用 VS Live Unit Testing 运行它,将其变为红色。将类从测试项目移到库中可能会也可能不会使该测试通过。
到目前为止,保持绿色的唯一方法是在继承的类中取消注释这一行。
// Changed.Subscribe(Console.WriteLine);
[TestClass]
public class StateBaseTests
{
#region Tests
[TestMethod]
public void State_ChangesToChanged_PropertyChanged()
{
var _item = new MyTest();
_item.Surname = "Testname";
Assert.AreEqual(Statetype.Changed, _item.State);
}
#endregion
#region SubClasses
public enum Statetype
{
Added,
Changed,
Deleted,
Detached,
Unchanged
}
public abstract class StateBase : ReactiveObject
{
protected StateBase()
{
State = Statetype.Unchanged;
Changed.Select(prop => prop.PropertyName)
.Subscribe(UpdateZustand);
}
protected void UpdateZustand(string propertyName)
{
if(State == Statetype.Unchanged)
State = Statetype.Changed;
}
[Reactive]
public Statetype State { get; set; }
}
private class MyTest : StateBase
{
public MyTest()
{
// Changed.Subscribe(Console.WriteLine);
}
[Reactive]
public string Name { get; set; }
[Reactive]
public string Surname { get; set; }
}
}
最佳答案
这是对您的样本的轻微改编。是使用 VS Mac Community & NUnit 实现的吗?每次在我的机器上测试都会变绿。如您所见,还打印了属性名称。在我的控制台上它输出:
State
Surname
代码如下:
using System;
using System.Reactive.Linq;
using NUnit.Framework;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace Testy {
[TestFixture]
public class Test {
[Test]
public void State_ChangesToChanged_PropertyChanged() {
var _item = new MyTest();
_item.Surname = "Testname";
Assert.AreEqual(Statetype.Changed, _item.State);
}
}
public enum Statetype {
Added,
Changed,
Deleted,
Detached,
Unchanged
}
public abstract class StateBase : ReactiveObject {
protected StateBase() {
State = Statetype.Unchanged;
Changed
.Select(prop => prop.PropertyName)
.Subscribe(
name => {
UpdateZustand(name);
Console.WriteLine(name);
});
}
protected void UpdateZustand(string propertyName) {
if (State == Statetype.Unchanged)
State = Statetype.Changed;
}
[Reactive]
public Statetype State { get; set; }
}
public class MyTest : StateBase {
[Reactive]
public string Name { get; set; }
[Reactive]
public string Surname { get; set; }
}
}
不确定这是否有帮助,但尝试一下很有趣 :)。
PS:这些是使用过的包版本:
- ReactiveUI(.Fody) 10.5.1
- Nunit 3.12.0
- NUnit3TestAdapter 3.15.1
关于c# - 观察继承类的 ReactiveObject.Changed 可能有效也可能无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292333/