簡體   English   中英

如何為包含異步服務調用的 RelayCommand 編寫單元測試?

[英]How do I write a Unit test for a RelayCommand that contains an Async Service Call?

我有一個要測試的RelayCommand RelayCommand包含用於驗證我的用戶的Service Call 如下圖:

private MvxCommand _signIn;
public MvxCommand SignIn
{
    get
    {
        return _signIn ?? (_signIn = new MvxCommand(() =>
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            EndpointAddress endpoint = new EndpointAddress(AppResources.AuthService);
            var client = new MyService(binding, endpoint);
            client.AuthorizeCompleted += ((sender, args) =>
            {
                try
                {
                    if (args.Result)
                    {
                        //Success.. Carry on
                    }
                }
                catch (Exception ex)
                {
                    //AccessDenied Exception thrown by service
                    if (ex.InnerException != null && string.Equals(ex.InnerException.Message, "Access is denied.", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //Display Message.. Incorrect Credentials
                    }
                    else
                    {
                        //Other error... Service down?
                    }
                }
            });

            client.AuthorizeAsync(UserName, Password, null);

        }));
    }
}

但是現在我正在使用NUnit來測試我的ViewModels ,我對如何測試我的RelayCommand

我可以:

[Test]
public void PerformTest()
{
    ViewModel.SignIn.Execute();
}

但這不會返回有關SignIn方法是否成功的信息。

如何測試包含Service CallRelayCommand

所以最后我使用Dependency Injection將服務注入到我的視圖模型的構造函數中,如下所示:

public IMyService client { get; set; }

public MyClass(IMyService myservice)
{
    client = myservice
}

然后我可以像這樣重構我的SignIn方法:

private MvxCommand _signIn;
public MvxCommand SignIn
{
    get
    {
        return _signIn ?? (_signIn = new MvxCommand(() =>
        {
            client.AuthorizeCompleted += ((sender, args) =>
            {
                try
                {
                    if (args.Result)
                    {
                        //Success.. Carry on
                    }
                }
                catch (Exception ex)
                {
                    //AccessDenied Exception thrown by service
                    if (ex.InnerException != null && string.Equals(ex.InnerException.Message, "Access is denied.", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //Display Message.. Incorrect Credentials
                    }
                    else
                    {
                        //Other error... Service down?
                    }
                }
            });
            client.AuthorizeAsync(UserName, Password, null); 
        }));
    }
}

並使用 Assign-Act-Assert 設計模式使用模擬服務測試我的ViewModel

    [Test]
    public void PerformTest()
    {
        List<object> objs = new List<object>();
        Exception ex = new Exception("Access is denied.");
        objs.Add(true);

        AuthorizeCompletedEventArgs incorrectPasswordArgs = new AuthorizeCompletedEventArgs(null, ex, false, null);
        AuthorizeCompletedEventArgs correctPasswordArgs = new AuthorizeCompletedEventArgs(objs.ToArray(), null, false, null);

        Moq.Mock<IMyService> client = new Mock<IMyService>();

        client .Setup(t => t.AuthorizeAsync(It.Is<string>((s) => s == "correct"), It.Is<string>((s) => s == "correct"))).Callback(() =>
        {
            client.Raise(t => t.AuthorizeCompleted += null, correctPasswordArgs);
        });


        client.Setup(t => t.AuthorizeAsync(It.IsAny<string>(), It.IsAny<string>())).Callback(() =>
        {
            client.Raise(t => t.AuthorizeCompleted += null, incorrectPasswordArgs);
        });

        var ViewModel = new MyClass(client.Object);

        ViewModel.UserName = "correct";
        ViewModel.Password = "correct";
        ViewModel.SignIn.Execute();
    }

暫無
暫無

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

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