gpt4 book ai didi

c# - 有没有办法将任何函数调用一般地包装在 try/catch block 中?

转载 作者:太空狗 更新时间:2023-10-30 00:57:59 24 4
gpt4 key购买 nike

我正在为一个项目编写一堆集成测试。我想调用包含在 try/catch block 中的每个单独的集成点方法,这样当它失败时,我会得到某种反馈来显示,而不仅仅是让应用程序崩溃。我还希望能够计算调用时间,并在需要时检查返回值。因此,我有一个 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 方法作为参数和委托(delegate)或其他东西传递进来以检查结果,但我不知道这是否可能。是否有任何框架可以处理此类测试,或者您对我如何简化代码以更好地重用有什么建议吗?我厌倦了输入这个 block ;)

最佳答案

(我假设这是 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;
});
}

这可以很容易地扩展到包括您的时间安排。

关于c# - 有没有办法将任何函数调用一般地包装在 try/catch block 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3892156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com