17

I have a question on unit testing the Main method of a console app. The standard signature is

  public static void Main(string[] args)

I want to be able to test to ensure that only 1 parameter is passed in. If more than one parameter is passed in that i want the test to fail.

I don't think i can mock this with MOQ as its a static method.

Anyone have any experience with this?

Any ideas ?

Thanks

Martin
  • 23,844
  • 55
  • 201
  • 327
  • Why would you need to mock it? Does it have dependencies that cannot be called? – Davin Tryon Jul 01 '14 at 09:54
  • Input should be checked at run time inside your main method. Why is this crucial for your unit test? – SBI Jul 01 '14 at 09:55
  • Just a note for future readers: The signature can be changed to `static int Main` and I sometimes make use of that return signal to create unit tests – Simeon Dec 13 '14 at 21:09

2 Answers2

29

There is nothing to mock in your scenario. Static Program.Main is a method just as any other and you test it as such -- by invoking it.

The issue with static void method is that you can only verify whether it throws exception or interacts with input argument (or other static members, eventually). Since there is nothing to interact with on string[] you can test former case.

However, a more sound approach is to delegate all logic contained in Main to separate component and test it instead. Not only this allows you to test your input argument handling logic thoroughly but also simplifies Main to more or less this:

public static void Main(string[] args)
{
    var bootstrapper = new Bootstrapper();
    bootstrapper.Start(args);
}
k.m
  • 30,794
  • 10
  • 62
  • 86
1

Integration test

ProgramTest.cs

using NUnit.Framework;

namespace Tests;

public class ConsoleTests
{
    [Test]
    public void ProhibitsMoreThanOneArgument()
    {
        var capturedStdOut = CapturedStdOut(() =>
        {
            RunApp(arguments: new string[] { "argument1", "argument2" });
        });

        Assert.AreEqual("Passing two arguments is not supported.", capturedStdOut );
    }

    void RunApp(string[]? arguments = default)
    {
        var entryPoint = typeof(Program).Assembly.EntryPoint!;
        entryPoint.Invoke(null, new object[] { arguments ?? Array.Empty<string>() });
    }

    string CapturedStdOut(Action callback)
    {
        TextWriter originalStdOut = Console.Out;

        using var newStdOut = new StringWriter();
        Console.SetOut(newStdOut);

        callback.Invoke();
        var capturedOutput = newStdOut.ToString();

        Console.SetOut(originalStdOut);

        return capturedOutput;
    }
}

Implementation

Program.cs

if (args.Length > 1)
{
    Console.WriteLine("Passing two arguments is not supported.");
}
Artur INTECH
  • 6,024
  • 2
  • 37
  • 34