Hoang Minh Hoang Minh - 2 months ago 13
C# Question

Unit Test for Bank class in C#

I'm learning to create unit tests for project written in C#. I've been follow the example on the MSDN website and now I just got stuck at how create a unit test when the amount is less than zero. The unit test is supposed to be failed when I run it. However, the way that I've written below, it passed :(
Would someone please let me know what I need to do to fix it ? Thanks

Here is what I have so far:

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


This is the method that I'm testing on

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

Answer

The test looks just fine, you expect an exception when amount is negative and it's throwing exception, otherwise it won't pass. Although in this kind of tests, I usually have something like this at the end.

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

That Assert will fail the test in case the exception is not thrown when expected.

Comments