Home > database >  How does unit test project test main()
How does unit test project test main()

Time:02-06

I have a simple .net core console project in VS2019 as follows.

public class Program
{ 
   public static int Sum(int x, int y) 
   { 
      return x   y; 
   } 
   public static void Main(string[] args) 
   { 
      Func<int, int, int> sum = Sum; 
      Console.WriteLine(sum(10, 10)); 
   } 
}

My question is how to create a unit test project to test main().

CodePudding user response:

The static void method is that you can only verify if it interacts with the input argument or static members. A better approach is to delegate all logic to separate component and test it instead. Then it doesn't matter which type of project it is. You can just create a Unit Test project and test your code.

public static void Main(string[] args)
{
   var component = new Component();
   component.Execute(args);
}

Example component:

public class Component
{
    public static int Sum(int x, int y)
        => x   y;

    public void Execute(string[] args)
    {
        Func<int, int, int> sum = Sum;
        Console.Write(sum(10, 10));
    }
}

Test:

   [Fact]
   public void Test()
   {
       //assert
       var stringWriter = new StringWriter();
       Console.SetOut(stringWriter);

       var component = new Component();
       component.Execute(It.IsAny<string[]>());
       var output = stringWriter.ToString();
       Assert.Equal("20", output);
   }
  •  Tags:  
  • Related