Unit testing the Viewmodel

前端 未结 6 2081
既然无缘
既然无缘 2021-02-05 18:03

I am sort of new to TDD. I have started creating the properties I need on the view model as plain auto property.

public string Firstname { get; set; }

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 18:54

    Here's how I've done this in the past (I've used NUnit so it might be a bit different):

    [Test]
    public void ShouldNotifyListenersWhenFirstNameChanges()
    {
        var propertiesChanged = new List();
    
        ViewModel = new CustomerViewModel();
        ViewModel.PropertyChanged += (s, e) => propertiesChanged.Add(e.PropertyName);
    
        ViewModel.Firstname = "Test";
    
        Assert.Contains("Firstname", propertiesChanged);      
        Assert.AreEqual("Test", ViewModel.Firstname);  
    }
    

    Has the nice side-effect of being able to debug and work out what changed, if it wasn't the Firstname. Really handy when you've got multiple fields being calculated from other fields. You can also look at the other aspect of behaviour in your code:

    [Test]
    public void ShouldNotNotifyListenersWhenPropertiesAreNotChanged()
    {
        var propertiesChanged = new List();
    
        ViewModel = new CustomerViewModel();
        ViewModel.Firstname = "Test";
    
        ViewModel.PropertyChanged += (s, e) => propertiesChanged.Add(e.PropertyName);
    
        ViewModel.Firstname = "Test";
    
        Assert.AreEqual(0, propertiesChanged.Count); 
    }
    

提交回复
热议问题