有没有一种方法可以将任何函数调用包装在 try/catch 块中?

发布于 2024-09-26 12:50:07 字数 1302 浏览 2 评论 0原文

我正在为一个项目编写一堆集成测试。我想调用包含在 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 方法作为参数和委托或其他内容传递给检查结果,但我不知道这是否可能。是否有任何框架可以处理此类测试,或者您对如何简化代码以更好地重用有什么建议吗?我厌倦了输入这个块;)

I am writing a bunch of integration tests for a project. I want to call each individual integration point method wrapped in a try/catch block so that when it fails, I get some sort of feedback to display, rather than just crashing the app. I also want to be able to time how long the calls take, and check return values when needed. So, I have an IntegrationResult class with some basic description, result and time elapsed properties:

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();
  }
}

The code I keep writing looks like this:

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);
    }

I would really like to be able to just pass the SomeIntegrationPoint method in as an argument and a delegate or something to check the results, but I can't figure out if that's even possible. Are there any frameworks to handle this type of testing, or do you have any suggestions on how I might simplify the code for better reuse? I'm tired of typing this block ;)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愛放△進行李 2024-10-03 12:50:07

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

这也可以轻松扩展以包括您的计时。

(I'm assuming this is C#, as tagged... though the syntax was not in the question.)

You can do this. Just change your result class to include:

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;
      }
       ...

You could then change your code for your tests to:

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;
    });
 }

This can easily be extended to include your timings as well.

朱染 2024-10-03 12:50:07

您研究过 AOP 吗? PostSharp 看起来是一个不错的起点。还有一个关于异常处理方面的示例

Have you looked into AOP? PostSharp looks like a nice place to start. There is also an example on exception handling aspects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文