Check Console Output In Unit Test

Viewed 14085

Is there a way I can check what is the output to the console in my unit test of my abstract class Question?

I am using NUnit & Moq.

My unit test looks like this:

    [Test]
    public void QuestionAsk()
    {
        var mock = new Mock<Question>(new object[]{"question text",true});

        mock.CallBase = true;

        var Question = mock.Object;

        Question.Ask();

        mock.Verify(m => m.Ask(), Times.Exactly(1));

    }

Here I am checking that Question.Ask() is called and it works fine. Ask() does not return a value so I cannot assign it to a variable. The function just outputs to the console.

Is there a way I can verify in the test that the output == "question text" ?

EDIT: Forgot to mention Question is an abstract base class.

I tried the Concole.Setout method suggested with this code:

    [Test]
    public void QuestionAsk()
    {
        var mock = new Mock<Question>(new object[]{"question text",true});

        mock.CallBase = true;

        var Question = mock.Object;

        using (var consoleText = new StringWriter())
        {
            Console.SetOut(consoleText);
            Question.Ask();
            Assert.That(consoleText.ToString(), Is.StringMatching("question text"));
        }
        mock.Verify(m => m.Ask(), Times.Exactly(1));

    }

But it took 236 ms which is far too long for a test. Implementing the IWriter interface seems the best way to deal with it so I will give that a go now.

2 Answers
Related