不会在setter中抛出异常

时间:2018-03-11 16:49:48

标签: c# xunit

我创建了一个班级" BankAccount.cs"我正在使用xunit来测试它。我测试构造函数是否抛出ArgumentException,如果它提供了一个空字符串作为参数(参数是银行帐号作为字符串)。

我的测试失败了,因为没有抛出异常 - 我无法找出原因。

看起来构造函数甚至没有被调用;如果我让构造函数抛出一个Exception(而不是在AccountNumber的setter中实现它),也不会抛出任何一个。此外,如果我使用Console.WriteLine手动调试,则不会向控制台写入任何内容。

异常(调试)设置为默认设置。

using System;
using System.Collections.Generic;

namespace Banking.Models
{
    public class BankAccount : IBankAccount
    {
        /* NOTE: I've deleted non-relevant fields, properties and methods for brevity */

        private string _accountNumber;

        public string AccountNumber
        {
            get { return _accountNumber; }
            set
            {
                if(value == string.Empty)
                    throw new ArgumentException("Accountnumber must have a value");
                _accountNumber = value;
            }
        }

        public BankAccount(string account)
        {
            AccountNumber = account;
            Balance = Decimal.Zero;
            _transactions = new List<Transaction>();
        }

        public override string ToString()
        {
            return $"{AccountNumber} - {Balance}";
        }
        public override bool Equals(object obj)
        {
            BankAccount account = obj as BankAccount;
            if (account == null) return false;
            return AccountNumber == account.AccountNumber;
        }
        public override int GetHashCode()
        {
            return AccountNumber?.GetHashCode() ?? 0;
        }
    }
}

试验:

using System;
using Xunit;
using Banking.Models;

namespace Tests.Models
{
    public class BankAccountTest : IDisposable
    {
        // private variables
        private BankAccount _account;
        private string AccountNumber { get; set; }

        // Setup
        public BankAccountTest()
        {
            AccountNumber = "123-4567890-02";
            _account = new BankAccount(AccountNumber);
        }

        [Fact]
        public void NewAccount_BalanceZero()
        {
            Assert.Equal(0, _account.Balance);
        }

        [Fact]
        public void NewAccount_CorrectAccountNumber()
        {
            Assert.Equal(AccountNumber, _account.AccountNumber);
        }

        [Fact]
        public void NewAccount_EmptyString_Fails()
        {
            Assert.Throws<ArgumentException>(
                () => new BankAccount(string.Empty));
        }

        // TearDown
        public void Dispose()
        {

        }
    }
}

0 个答案:

没有答案