【问题标题】:Unit testing a controller in ASP.NET MVC 3 [closed]在 ASP.NET MVC 3 中对控制器进行单元测试 [关闭]
【发布时间】:2012-11-03 21:08:38
【问题描述】:
public Double Invert(Double? id)
{
    return (Double)(id / id);
}

我已经为这个测试做了这个但是失败了请任何人帮助这个因为刚开始单元测试

/* HINT:  Remember that you are passing Invert an *integer* so
 * the value of 1 / input is calculated using integer arithmetic. 
 * */
//Arrange
var controller = new UrlParameterController();
int input = 7;
Double expected = 0.143d;
Double marginOfError = 0.001d;

//Act
var result = controller.Invert(input);

//Assert
Assert.AreEqual(expected, result, marginOfError);

/* NOTE  This time we use a different Assert.AreEqual() method, which
 * checks whether or not two Double values are within a specified
 * distance of one another.  This is a good way to deal with rounding
 * errors from floating point arithmetic.  Without the marginOfError 
 * parameter the assertion fails.
 * */  

【问题讨论】:

  • 我没有看到问题,请在您的帖子中更具体。
  • 这似乎更多地是关于浮点运算而不是单元测试。 Assert 的结果是什么?
  • 你为什么使用可以为空的 Double?无论如何,除以 null 是不可能的,所以它只会导致一个神秘的错误。
  • @aulme: 除以 null 不是不可能,它只是 null msdn.microsoft.com/en-us/library/2cf62fcy(v=vs.80).aspx "预定义的一元和二元运算符以及为值类型存在的任何用户定义的运算符可能也可用于可空类型。如果操作数为空,这些运算符会产生空值;否则,运算符将使用包含的值来计算结果。但是,当然,转换回不可为空的类型会失败。
  • @JayC -“System.InvalidOperationException:可空对象必须有一个值。”你不能在这里使用null作为id并尝试划分。

标签: c# .net asp.net-mvc-3 unit-testing controller


【解决方案1】:

您似乎想测试您的控制器以“反转”一个值。 如果你不将一个值单独划分,它可能会有所帮助。

唯一可能发生的事情是:

  1. 你会得到“1”的结果(提示,提示)
  2. 你得到“NaN”(0/0)
  3. 传入 null 会导致转换错误。

【讨论】:

    【解决方案2】:

    浏览您的代码示例,我认为您正在寻找的是控制器中的逆方法。

    public Double Invert(Double? id)
    {
        //replace id with 1 -- (1/id) gives you an inverse of id.  
        return (Double)(1 / id);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多