簡體   English   中英

C#中的異步方法測試

[英]Asynchronous method testing in C#

我有以下事件處理程序-使用Dispatcher.BeginInvoke,我認為它與在BeginInvoke上類似的另一個堆棧溢出問題不同:

private void source_load_complete()
    {
        Dispatcher.BeginInvoke( new NotificationDelegate( source_load_complete_ui ), null );
    }

接着:

private void source_load_complete_ui()
    {
        m_image.Image = m_bmp.CreateBitmap();
        m_image.UpdateImage( null );
        m_image.LoadComplete = true;
        raise_property_changed( "CurrentImage" );
    }

為了對此進行測試,請使用以下測試方法:

[TestMethod]
    public void ImageVM_SourceLoadTests()
    {
        ImageViewModel ivm = new ImageViewModel();
        List<string> eventList = new List<string>();

        ivm.PropertyChanged += delegate( object sender, System.ComponentModel.PropertyChangedEventArgs e )
        {
            eventList.Add( e.PropertyName );
        };

        // check the model is set up correctly so the event in the constructor works
        CustomImage model = ivm.ImageModel as CustomImage;
        WriteableBitmap bmp = model.Image;

        if( model.ImageSource.LoadComplete != null )
        {
// fire off the event we want to test is handled correctly
            model.ImageSource.LoadComplete();
        }

        Assert.IsTrue( model.LoadComplete == true);
        Assert.IsTrue( model.Image == bmp );
        Assert.IsTrue( eventList.Count == 1 );
    }

顯然,這是行不通的,因為source_load_complete_ui方法是異步調用的。 但是,在搜索如何最好地測試它並等待異步方法被調用之后,我無法弄清楚。

編輯:我沒有提到該類繼承Dispatcher對象,因此BeginInvoke與給出的答案無關:

public class ImageViewModel : DispatcherObject, INotifyPropertyChanged

因此,建議不要重復

最后,我發現這個答案實際上與此答案有關。 在單元測試中使用WPF Dispatcher

使用此答案中描述的調度程序助手實用程序,可以強制它處理隊列並在單元測試中使用它。

public static class DispatcherUtil
{

[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents()
{
    DispatcherFrame frame = new DispatcherFrame();
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
        new DispatcherOperationCallback(ExitFrame), frame);
    Dispatcher.PushFrame(frame);
}

private static object ExitFrame(object frame)
{
    ((DispatcherFrame)frame).Continue = false;
    return null;
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM