Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Unit Testing(Nunit) the Main method of a console app?

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

like image 419
Martin Avatar asked Jul 01 '14 09:07

Martin


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

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);
}
like image 56
k.m Avatar answered Oct 25 '22 01:10

k.m