Unit testing the Viewmodel

前端 未结 6 2086
既然无缘
既然无缘 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条回答
  •  梦毁少年i
    2021-02-05 18:36

    You could try writing the test to be asynchronous. Consider this test method:

    [TestMethod]
    [Asynchronous]
    public void TestMethod1()
    {
        TestViewModel testViewModel = new TestViewModel();
    
        bool firstNameChanged = false;
    
        testViewModel.PropertyChanged +=
            (s, e) =>
                {
                    if (e.PropertyName == "FirstName")
                    {
                        firstNameChanged = true;
                    }
                };
    
        EnqueueCallback(() => testViewModel.FirstName = "first name");
        EnqueueConditional(() => firstNameChanged == true);
        EnqueueTestComplete();
    }
    

    Notice the Asynchronous attribute at the top of the method. There are two important methods here: EnqueueCallback and EnqueueTestComplete. EnqueueCallback will add lambda expressions to a queue and the test method will wait until the current callback is executed. In the case here, we subscribe to the PropertyChanged event on the ViewModel and we set a local boolean variable to true when the FirstName property notifies a change. We then Enqueue two callbacks: one to set the FirstName property and one to assert that the local boolean variable has changed value. Finally, we need to add a call to EnqueueTestComplete() so that the framework knows the test is over.

    NOTE: In order to get EnqueueCallback and EnqueueTestComplete, you need to inherit from SilverlightTest on your test class. You also need to import Microsoft.Silverlight.Testing to get the Asynchronous attribute. It should look something like this:

    using Microsoft.Silverlight.Testing;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace Foo.Example.Test
    {
        [TestClass]
        public class Tests : SilverlightTest
        {
    
            // ... tests go here
        }
    }
    

提交回复
热议问题