如何重构测试应用程序?

vor*_*rou 4 c# testing refactoring

我有一个测试应用程序,有一个类TestSeq和一个方法Go(),它包含这样的块:

            _writer.WriteLine("Doing foo action...");
            var stopwatch = Stopwatch.StartNew();
            // foo - some work here
            stopwatch.Stop();
            _writer.WriteDone("Results of foo action.", stopwatch.Elapsed);
Run Code Online (Sandbox Code Playgroud)

在"一些工作"中,我对WCF客户端有不同的调用(CRUD操作,过滤器等).

所以,很多代码都在重复,显然有些重构应该在这里完成.我想创建一个类TestAction,但我不知道什么是将"一些工作"放在其中的最佳方法.

在我看来,这是一个非常简单的问题,但我不知道应该搜索哪些关键字.所以,我很高兴看到只有一个关键字(模式名称或东西)或链接的答案.

Dav*_* Z. 5

我确信还有更多,但在我的头顶,你可能有两种方式可以用这个锅炉板代码.

方法1:使用using语法来包装感兴趣的代码

class MeasuredOperation : IDisposable
{
    Stopwatch stopwatch;
    string message;

    public MeasuredOperation(string message)
    {
        Console.WriteLine("Started {0}", message);
        stopwatch = Stopwatch.StartNew();
        this.message = message;
    }

    public void Dispose()
    {
        stopwatch.Stop();
        Console.WriteLine("Results of {0} Elapsed {1}", this.message, this.stopwatch.Elapsed);
    }
}

    static void Main(string[] args)
    {
        using (new MeasuredOperation("foo action"))
        {
            // Do your action
        }
    }
Run Code Online (Sandbox Code Playgroud)

方法2:创建一个新函数并将代码块作为委托传递

static void MeasuredAction(string message, Action action)
{
    Console.WriteLine("Started {0}", message);
    var stopwatch = Stopwatch.StartNew();
    action();
    stopwatch.Stop();
    Console.WriteLine("Results of {0} Elapsed {1}", message, stopwatch.Elapsed);
}

static void Main(string[] args)
{
    MeasureAction(delegate()
    {
        // do work
    });
}
Run Code Online (Sandbox Code Playgroud)