2014-07-25 46 views
0

我正在学习为用C#编写的项目创建单元测试。我一直在MSDN网站上进行示例,现在我只是在数量小于零时如何创建单元测试。当我运行它时,单元测试应该失败。不过,我已经写在下面的方法,它通过:( 会有人请让我知道我需要做修复它感谢C中银行类的单元测试#

这是我到目前为止有:?

 // unit test method 
     [TestMethod] 
     [ExpectedException(typeof(ArgumentOutOfRangeException))] 
     public void Debit_WhenAmountIsLessThanZero_ShouldThrowArgumentOutOfRange() 
     { 
      // arrange 
      double beginningBalance = 11.99; 
      double debitAmount = -100.00; 


      BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance); 

      // act 
      account.Debit(debitAmount); 

      // Not sure about this one 
      // on my main program, I use if...else to handle 
      // the situation when amount > balance by throwing the exception 
      double actual = account.Balance; 
      Assert.IsTrue(actual < 0, "Actual balance is greater than 0");    
     } 

这是我在

 public void Debit(double amount) 
     { 
      if (m_frozen) 
      { 
       throw new Exception("Account frozen"); 
      } 

      if (amount > m_balance) 
      { 
       throw new ArgumentOutOfRangeException("amount"); 
      } 

      if (amount < 0) 
      { 
       throw new ArgumentOutOfRangeException("amount"); 
      } 

      m_balance -= amount; 
     } 
+1

您还应该添加BankAccount类的代码。 – EfrainReyes

+1

如果BankAccount#Debit引发异常,Assert代码将永远不会到达,因此您的测试将会成功,因为您预计会发生异常 – Machinarius

+0

'Assert.IsTrue(实际<0,“实际余额大于0”); '倒退了。您断言实际数量是**小于**零。 – Blorgbeard

回答

2

测试看起来只有精细,你期望一个异常时,金额为负并且它抛出异常检测方法,否则将无法通过。虽然这种测试,我通常在最后有这样的事情。

Assert.Fail("Should have thrown exception because of ........") 

Assert将失败的情况下,预计在没有抛出异常的考验。

+0

我现在认为我了解它的工作方式。谢谢你的解释。 –

1

你可以这样做:

Assert.AreEqual(beginningBalance - debitAmount, account.Balance); 

验证该值是你所期望的,而不是仅仅小于零。

1

由于个人喜好,我喜欢当我所有的测试都成功:)所以我会写这样的事:

var exception = Assert.Throws<ArgumentOutOfRangeException>(() => account.Debit(debitAmount)); 
Assert.That(exception.ParamName, Is.Equal("amount")); 

,可能的话,抛出不同类型的异常和消息对他们的。