Class method outputs string message, can't unit test due error citing conversion from void to string not applicable

Viewed 161

I'm quite new to unit testing. So far, I'm able to successfully unit test methods that return a data type, such as enum types, integer types, and string types. However, I can't seem to unit test void return type methods that outputs a string, it says unable to convert 'void' to string. There isn't a return type. The code below should clarify my problem. This is the method:

public void Details()
    {
        if (_type == AccountType.FixedDeposit)
        {
            Console.WriteLine(String.Format("Fixed Deposit Account:{0,-5}Balance:{1}", _accNumber, _balance));
        }
        else
        {
            Console.WriteLine(String.Format("{0,-13} Account:{1,-5}Balance:{2}", _type, _accNumber, _balance));
        }

This is the unit test code:

[TestCase]
    public void TestDetails()
    {
        BankAccount b = new BankAccount(111, AccountType.Saving);
        b.Deposit(1000);
        b.Withdraw(500);
        StringAssert.AreEqualIgnoringCase("Saving       Account:111  Balance:500", b.Details());
    }

I expected it to output a string that is able to compare too.

1 Answers

Change Details to return the string instead of printing it out:

public string Details()
{
    if (_type == AccountType.FixedDeposit)
    {
        return String.Format("Fixed Deposit Account:{0,-5}Balance:{1}", _accNumber, _balance);
    }
    else
    {
        return String.Format("{0,-13} Account:{1,-5}Balance:{2}", _type, _accNumber, _balance);
    }
}

Note that you'll have to change your "production" code and add the Console.WriteLine calls to the places that called Details.

Related