简体   繁体   中英

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

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.

you could do this:

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

to verify the value is what you expect, instead of just less than zero.

As a personal preference, I like when all my tests are successful :) So I would write something like this:

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

And, possibly, throw different types of exceptions and message for them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM