【问题标题】:Contract.Ensures for an OverFlowException一个 OverFlowException 的 Contract.Ensures
【发布时间】:2013-04-21 04:51:13
【问题描述】:

我有一个简单的方法,可以返回给定数字的指数值:

    public int Exp(int num)
    {
        return Convert.ToInt32(System.Math.Exp(num));
    }

运行 Pex 时,我在 Summary/Exception 字段中得到一个 OverFlowException,用于某个大数字:1969057606。

如何使用Contract.Ensure() 创建发布条件? 我尝试了以下方法,但它没有做任何事情:

Contract.Ensures(Contract.Result<int>() < 2147483647);

// This is because the max value an int variable can hold is 2147483647

【问题讨论】:

  • 你应该使用int.MaxValue而不是实际的数字,这对于查看代码的人来说更容易阅读和解析。
  • 非常感谢加布里埃尔。那是真实的!感谢您的帮助!

标签: class pex contract overflowexception


【解决方案1】:

Contract.Ensures 用于在函数运行后断言类的状态,或者在这种情况下,无论输入是什么,都断言函数的结果。您需要添加一个 Contract.Requires 使得 e^num

Contract.Requires<ArgumentOutOfRangeException>(num <= Math.Floor(Math.Log(int.MaxValue)))

虽然您可能希望将最大值计算提取到一个常数中。

public static readonly int MAX_EXPONENT = Math.Floor(Math.Log(int.MaxValue));
...
Contract.Requires<ArgumentOutOfRangeException>(num <= MAX_EXPONENT)

【讨论】:

  • 布莱恩,非常感谢您的帮助!你的解释帮助我解决了主要问题。再次感谢!
猜你喜欢
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
相关资源
最近更新 更多