1

我使用FluentAssertions來檢查視圖模型。我想驗證是否正確地提升了屬性的PropertyChanged事件。如何檢查在爲所有屬性進行內部提升時使用FluentAssertions發送信號的屬性更改?

信號單獨的屬性時,這是工作的罰款:

public string MyName { 
    get => this.myName; 
    set => { 
    this.myName = value; 
    this.FirePropertyChanged(nameof(this.MyName)); 
    } 
} 
... 
sut.MonitorEvents(); 
sut.ShouldRaisePropertyChangeFor(model => model.MyName); // OK 

一些複雜的視圖模型要刷新所有特性,並提出nullstring.Empty這將導致以刷新(MSDN)。 但FluentAssertions調用不接受這作爲有效的更改。

public string IsServer { 
    get => this.isServer; 
    set => { 
    this.isServer = value; 
    this.FirePropertyChanged(string.Empty); 
    } 
} 
... 
sut.MonitorEvents(); 
sut.ShouldRaisePropertyChangeFor(model => model.IsServer); // FAILED 

有沒有一個選項來檢查這樣的事件?

回答

0

應該(無雙關語意)能夠呼叫sut.ShouldRaisePropertyChangeFor(null)

+0

'null'有效,但不適用於'string.Empty'。爲該邊緣情況創建了額外的擴展程序。 – Nkosi

1

ShouldRaisePropertyChangeFor期望一個表達式,雖然適用於null不適用於空字符串。仍然可以使用ShouldRaise來檢查PropertyChanged事件是否與特定的PropertyChangedEventArgs一起引發。

鑑於

public string IsServer { 
    get => this.isServer; 
    set => { 
    this.isServer = value; 
    this.FirePropertyChanged(string.Empty); 
    } 
} 

具有以下測試

//Arrange 
var sut = new Sut(); 

sut.MonitorEvents(); 

//Act 
sut.IsServer = "Hello World"; 

//Assert 
sut.ShouldRaise("PropertyChanged") 
    .WithArgs<PropertyChangedEventArgs>(e => e.PropertyName == string.Empty); 

ShouldRaise(...).WithArgs<>(...)應滿足測試

上面可以封裝成的要求,是在原來的想法自己的擴展方法建設。

public static class AllPropertiesChangedSourceExtensions { 
    private const string PropertyChangedEventName = "PropertyChanged"; 
    public static FluentAssertions.Events.IEventRecorder ShouldRaisePropertyChangeFor<T>(this T eventSource, string propertyName) { 
     return eventSource.ShouldRaise(PropertyChangedEventName) 
      .WithSender(eventSource) 
      .WithArgs<PropertyChangedEventArgs>(args => args.PropertyName == propertyName); 
    } 
} 

並號召

//Assert 
sut.ShouldRaisePropertyChangeFor(string.Empty); //Or null depending on which was used 

順便說一句,當string.Emptynull事件稱爲實際上並不調用所有屬性提高。偵聽獲取這些值的事件的框架將基於空或空字符串作爲屬性名稱引發的事實來通知UI。

+0

感謝您的回覆,但它並沒有真正回答我的問題。也許它沒有完全描述。從用戶角度來看,我想驗證個人「PropertyChanged」的提升,甚至用'string.empty'提升實現。這種PropertyChanged與視圖無關,所以它應該與測試相關。 – LukasAIS

相關問題