Search code examples
c#dictionarytddnunitconsole.writeline

Test that I can iterate through dictionary and write keys and values to console


I'm trying to write a console application in C# (which I'm VERY new to) using TDD.

I'm trying to iterate through a dictionary containing strings as keys and integers as values, and output them to the console as "key: value". I've tried loads of different things and finally found something which might work:

    public void ShowContents ()
    {
        foreach (KeyValuePair<string, int> item in dictionary) {
            Console.WriteLine ("{0}: {1}", item.Key, item.Value);
        }
    }

The problem I'm having is - I don't know how to test this. My test looks like this at the moment:

[Test ()]
    public void CanShowContentsOfDictionary ()
    {
        dictionary.AddWord ("Hello");
        Assert.AreEqual ("Hello: 1", dictionary.ShowContents ());
    }

And is obviously expecting a return value rather than something being output to console. I read elsewhere on here that there was no point testing for Console.WriteLine as you just assume it works, and so instead you can use return in this method and then write another method that just writes to console (and therefore doesn't need to be tested). The problem with this is that a) I don't know how to write a method that returns all the keys and values; b) I'm not returning one thing, but a number of different strings.

Any advice as to how I go about this?


Solution

  • You could write a function to return the entire string that would have been output by ShowContents; something like:

    public string GetContents()
    {
        var sb = new StringBuilder();        
        foreach (KeyValuePair<string, int> item in dictionary) {
            sb.AppendLine(string.Format("{0}: {1}", item.Key, item.Value));
        }
        return sb.ToString();
    }
    

    Then your ShowContents is just:

    Console.Write(GetContents());
    

    And you can test that GetContents returns what you expect, without involving Console.WriteLine.