我正在为一个项目编写一系列集成测试。我想调用包装在try/catch块中的每个单独的集成点方法,这样当它失败时,我可以得到某种反馈来显示,而不仅仅是崩溃应用程序。我还希望能够计时调用需要多长时间,并在需要时检查返回值。因此,我有一个integrationresult类,它具有一些基本的描述、结果和经过的时间属性:
class IntegrationResult
{
private StopWatch _watch;
public string Description {get;set;}
public string ResultMessage {get;set;}
public bool TestPassed {get;set;}
public string TimeElapsed {get { return _watch == null ? "0" : _watch.Elapsed.TotalMilliseconds.ToString(); } }
public void Start()
{
_watch = StopWatch.StartNew();
}
public void Stop()
{
_watch.Stop();
}
}
我一直在写的代码如下:
IntegrationResult result = new IntegrationResult();
result.Description = "T-SQL returns expected results";
try
{
result.Start();
SomeIntegrationPoint("potential arguments"); //This is the line being tested
result.Stop();
//do some check that correct data is present
result.TestPassed = true;
result.ResultMessage = "Pulled 10 correct rows";
}
catch(Exception e)
{
result.TestPassed = false;
result.ResultMessage = String.Format("Error: {0}", e.Message);
}
我真的很想把someintegrationpoint方法作为一个参数和一个委托或其他东西传入来检查结果,但是我不知道这是否可能。是否有任何框架来处理这种类型的测试,或者您对如何简化代码以便更好地重用有何建议?我厌倦了打这个方块;)
最佳答案
(我假设这是C,标记为…尽管语法没有问题。)
你可以这么做。只需将结果类更改为包括:
class IntegrationResult
{
string Description { get; set; }
string SuccessResultMessage { get; set; }
string FailResultMessage { get; set; }
public IntegrationResult(string desc, string success, string fail)
{
this.Description = desc;
this.SuccessResultMessage = success;
this.FailResultMessage = fail;
}
public bool ExecuteTest(Func<IntegrationResult, bool> test)
{
bool success = true;
try
{
this.Start();
success = test(this);
this.Stop();
this.ResultMessage = success ?
this.SuccessResultMessage :
this.FailResultMessage;
this.TestPassed = true;
}
catch(Exception e)
{
this.TestPassed = false;
this.ResultMessage = String.Format("Error: {0}", e.Message);
success = false;
}
return success;
}
...
然后,您可以将测试的代码更改为:
private void myDoTestMethod(string argumentOne, string argumentTwo)
{
IntegrationResult result = new IntegrationResult(
"T-SQL returns expected results",
"Pulled 10 correct rows",
"Wrong number of rows received");
result.Execute( r=>
{
integrationPoint.call(argumentOne, argumentTwo);
//do some check that correct data is present (return false if not)
return true;
});
}
这可以很容易地扩展到包括您的时间安排。