What is the smoothest, most appealing syntax you've found for asserting parameter correctness in c#?

后端 未结 14 1968
一个人的身影
一个人的身影 2020-12-22 23:50

A common problem in any language is to assert that parameters sent in to a method meet your requirements, and if they don\'t, to send nice, informative error messages. This

14条回答
  •  忘掉有多难
    2020-12-23 00:32

    I tackled this exact problem a few weeks ago, after thinking that it is strange how testing libraries seem to need a million different versions of Assert to make their messages descriptive.

    Here's my solution.

    Brief summary - given this bit of code:

    int x = 3;
    string t = "hi";
    Assert(() => 5*x + (2 / t.Length) < 99);
    

    My Assert function can print out the following summary of what is passed to it:

    (((5 * x) + (2 / t.Length)) < 99) == True where
    {
      ((5 * x) + (2 / t.Length)) == 16 where
      {
        (5 * x) == 15 where
        {
          x == 3
        }
        (2 / t.Length) == 1 where
        {
          t.Length == 2 where
          {
            t == "hi"
          }
        }
      }
    }
    

    So all the identifier names and values, and the structure of the expression, could be included in the exception message, without you having to restate them in quoted strings.

提交回复
热议问题