c# – 有没有办法在try / catch块中一般地包装任何函数调用?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 有没有办法在try / catch块中一般地包装任何函数调用?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2481字,纯文字阅读大概需要4分钟。
内容图文
![c# – 有没有办法在try / catch块中一般地包装任何函数调用?](/upload/InfoBanner/zyjiaocheng/813/b1807118cfc94afc8887b8ac930b69af.jpg)
我正在为一个项目编写一堆集成测试.我想调用包含在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;
});
}
这可以很容易地扩展到包括你的时间.
内容总结
以上是互联网集市为您收集整理的c# – 有没有办法在try / catch块中一般地包装任何函数调用?全部内容,希望文章能够帮你解决c# – 有没有办法在try / catch块中一般地包装任何函数调用?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。