Консольный проект C # - NUnit для проверки сообщения проверки - PullRequest
1 голос
/ 10 марта 2019

У меня есть этот рабочий метод, который я хотел бы написать для него методом NUnit Test Case.Это консольный проект, который означает, что сообщение об ошибке будет напечатано с помощью метода Console.WriteLine, который у меня есть для этого в методе PrintMessage в классе Utility.Вторым параметром является управление Console.Color (красный для сообщений об ошибках) с логическим значением.

public void PlaceDeposit(BankAccount account, decimal _transaction_amt)
    {   
        if (_transaction_amt <= 0)
            Utility.PrintMessage("Amount needs to be more than zero. Try again.", false);
        else if (_transaction_amt % 10 != 0)
            Utility.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false);
        else if (!PreviewBankNotesCount(_transaction_amt))
            Utility.PrintMessage($"You have cancelled your action.", false);
        else
        {
            // Bind transaction_amt to Transaction object
            // Add transaction record - Start
            var transaction = new Transaction()
            {
                AccountID = account.Id,
                BankAccountNoTo = account.AccountNumber,
                TransactionType = TransactionType.Deposit,
                TransactionAmount = _transaction_amt,
                TransactionDate = DateTime.Now
            };

            repoTransaction.InsertTransaction(transaction);
            // Add transaction record - End


            account.Balance = account.Balance + _transaction_amt;


            ctx.SaveChanges();

            Utility.PrintMessage($"You have successfully deposited {Utility.FormatAmount(_transaction_amt)}", true);
        }
    }

Я создал еще один тестовый проект NUnit для тестирования вышеуказанного метода, который застрял с Assert.Должен ли я изменить приведенный выше метод, чтобы он возвращал строку (выходное сообщение метода), чтобы создать тестовый пример NUnit, или мне следует изменить исходный метод?

[TestFixture]
public class TestATMCustomer
{
    [TestCase]
    public void PlaceDeposit()
    {
        // Arrange
        BankAccount bankAccount = new BankAccount() {
              FullName = "John", AccountNumber=333111, CardNumber = 123, PinCode = 111111, Balance = 2300.00m, isLocked = false                 
        };

        decimal transactionAmount = 120;

        var atmCustomer = new MeybankATM();

        // Act

        // Act and Assert
        Assert.AreEqual(atmCustomer.PlaceDeposit(bankAccount, transactionAmount));
    }
}

Обновлен тестовый пример, но с ошибкой в ​​конструкторе MeybankATM

    // Arrange - Start
        var mock = new MockMessagePrinter();

        MeybankATM atmCustomer = new MeybankATM(new RepoBankAccount(), new RepoTransaction(), mock);


        BankAccount bankAccount = new BankAccount()
        {
            FullName = "John",
            AccountNumber = 333111,
            CardNumber = 123,
            PinCode = 111111,
            Balance = 2000.00m,
            isLocked = false
        };

        decimal transactionAmount = 0;

        // Arrange - End

        // Act
        atmCustomer.PlaceDeposit(bankAccount, transactionAmount);

        // Assert            
        var expectedMessage = "Amount needs to be more than zero. Try again.";
        Assert.AreEqual(expectedMessage, mock.Message);

1 Ответ

2 голосов
/ 10 марта 2019
class Program
{
    static void Main(string[] args)
    {
        var mock = new MockMessagePrinter();
        ATMCustomer atmCustomer = new ATMCustomer(mock, new RepoTransaction());
        atmCustomer.PlaceDeposit(new BankAccount(), 0);
        Console.WriteLine(mock.Message == "Amount needs to be more than zero. Try again.");
        Console.ReadLine();
    }
}

public class ATMCustomer
{
    private readonly IMessagePrinter _msgPrinter;
    private readonly IRepoTransaction _repoTransaction;

    public ATMCustomer(IMessagePrinter msgPrinter, IRepoTransaction repoTransaction)
    {
        _msgPrinter = msgPrinter;
        _repoTransaction = repoTransaction;
    }
    public void PlaceDeposit(BankAccount account, decimal _transaction_amt)
    {
        if (_transaction_amt <= 0)
            _msgPrinter.PrintMessage("Amount needs to be more than zero. Try again.", false);
        else if (_transaction_amt % 10 != 0)
            _msgPrinter.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false);
        else if (!PreviewBankNotesCount(_transaction_amt))
            _msgPrinter.PrintMessage($"You have cancelled your action.", false);
        else
        {
            // Bind transaction_amt to Transaction object
            // Add transaction record - Start
            var transaction = new Transaction()
            {
                AccountID = account.Id,
                BankAccountNoTo = account.AccountNumber,
                TransactionType = TransactionType.Deposit,
                TransactionAmount = _transaction_amt,
                TransactionDate = DateTime.Now
            };

            _repoTransaction.InsertTransaction(transaction);
            // Add transaction record - End


            account.Balance = account.Balance + _transaction_amt;


            //ctx.SaveChanges();

            //_msgPrinter.PrintMessage($"You have successfully deposited {Utility.FormatAmount(_transaction_amt)}", true);
        }
    }

    private bool PreviewBankNotesCount(decimal transactionAmt)
    {
        throw new NotImplementedException();
    }
}

public class MockMessagePrinter : IMessagePrinter
{
    private string _message;

    public string Message => _message;

    public void PrintMessage(string message, bool idontKnow)
    {
        _message = message;
    }
}

public interface IRepoTransaction
{
    void InsertTransaction(Transaction transaction);
}

public class RepoTransaction : IRepoTransaction
{
    public void InsertTransaction(Transaction transaction)
    {
        throw new NotImplementedException();
    }
}

public interface IMessagePrinter
{
    void PrintMessage(string message, bool iDontKnow);
}

public class BankAccount
{
    public decimal Balance { get; set; }
    public string AccountNumber { get; set; }
    public int Id { get; set; }
}

public class Transaction
{
    public int AccountID { get; set; }
    public string BankAccountNoTo { get; set; }
    public TransactionType TransactionType { get; set; }
    public decimal TransactionAmount { get; set; }
    public DateTime TransactionDate { get; set; }
}

public enum TransactionType
{
    Deposit
}

Я скопировал ваш код и изменил некоторые из них:

  1. Я рефакторинг вашего кода, чтобы использовать IMessagePrinter вместо Utility, чтобы я мог внедрить фиктивный объект, чтобы проверить, что было передано в метод PrintMessage
  2. Я не использовал NUnit - я просто использовал проект консоли для примера
  3. Я предположил, что используются типы данных / классы, но это не имеет значения

Надеюсьэто помогает

Редактировать для NUnit:

public class TestAtmCustomer
{
    [Test]
    public void Should_ShowZeroErrorMessage_OnPlaceDeposit_When_AmountIsZero()
    {
        var mock = new MockMessagePrinter();
        ATMCustomer atmCustomer = new ATMCustomer(mock, new RepoTransaction());
        atmCustomer.PlaceDeposit(new BankAccount(), 0);

        var expectedMessage = "Amount needs to be more than zero. Try again.";
        Assert.AreEqual(expectedMessage, mock.Message);
    }
}
...