簡體   English   中英

使用調用另一個方法的后台工作程序對void方法進行單元測試?

[英]Unit testing a void method with a background worker that calls another method?

請記住,我是單元測試的新手,所以請多多包涵。 我有一個使用后台工作程序的方法來調用我的解決方案中另一個項目中的類的方法,而我發現很難將我的大腦包在單元測試中。

基本上是該方法的作用:

public void VerifyLocation()
{
    this.IsBusy = true;

    using (BackgroundWorker worker = new BackgroundWorker())
    {
        worker.DoWork += (sender, e) =>
        {
            Context context = Profile.GetContext();

            AssetManagerService svc = new AssetManagerService(context);
            this.Status = svc.Login();

            if (this.Status == AssetManagerLoginStatus.Success)
            {
                //Do stuff
                this.ShowError = false;
            }
            else if (this.Status == AssetManagerLoginStatus.LocationDoesNotExst || this.Status == AssetManagerLoginStatus.LibraryTitleNotDetermined)
                this.ShowError = true;
            else
                this.ShowError = false;
        };

        worker.RunWorkerCompleted += (sender, e) =>
        {
            if (e.Error != null)
            {
                this.ShowError = true;
            }

            this.IsBusy = false;
        };

        worker.RunWorkerAsync();
    }
}

這是AssetManagerService的示例:

public class AssetManagerService
{
    //AssetManager is an abstract class
    private AssetManager provider = null;

    public AssetManagerService(UnityContext context)
    {
        this.Context = context;
        this.InitializeProvider();
    }

    private void InitializeProvider()
    {
        //Determine provider based on Context properties
    }

    public AssetManagerLoginStatus Login()
    {
        return this.provider.Login();
    }
}

顯然,我最關心的是調用了Login()方法。 我會使用Shim來控制DoWork期間發生的情況嗎? 我將使用Stub強制Login()返回特定值嗎? 這兩個概念對我來說都是很新的。 是否需要進行重構以使其可以進行單元測試? 如果是這樣,將需要進行哪些更改?

我將DoWork移至單獨的方法,因為用這種方法進行測試比嘗試測試異步/多線程代碼要容易得多。

如果您只需要測試登錄名是否被稱為模擬/填充程序,則可能是可行的方法。 同樣,通過構造函數將AssetManager模擬注入到AssetManagerService實例中會更容易。

此外,模擬接口更容易。 也許您可以從AssetManager中提取一個接口,對其進行模擬,然后通過構造函數將其注入到AssetManagerInstance中。 要模擬接口,您不一定需要填充程序。 像NSubstitute這樣的更簡單的模擬框架就可以完成這項工作。 使用NSubstitute,您還可以告訴模擬在調用Login()時返回特定值。

暫無
暫無

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

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