skip to Main Content

Image
I have got a requirement to write unit test for main method but i couldn’t do it in normal way
I have tried to do that by using
Image
but its failing or the process is not stopping . Is there any better approach to write unit test for main method

2

Answers


  1. The code as written isn’t testable as the method won’t return unless the console receives a signal to terminate the app as part of Run() (also having it private over-complicates calling it – you should make it public or internal and access it with [InternalsVisibleTo("...")]). However, if you refactored it to pull out most of the implementation, you could call that method and have the Main() method call that.

    using System.Diagnostics.CodeAnalysis;
    using Microsoft.AspNetCore.Builder;
    
    public static class Program
    {
        [ExcludeFromCodeCoverage]
        private static void Main(string[] args)
        {
            WebApplication app = Bootstrap(args);
            app.Run();
        }
    
        public static WebApplication Bootstrap(string[] args)
        {
            WebApplicationBuilder builder = new WebApplication.CreateBuilder(args);
    
            // Your code here
    
            WebApplication app = builder.Build();
    
            // Your other code here
    
            return app;
        }
    }
    
    public static class MyUnitTests
    {
        [Fact]
        public static void TestSomething()
        {
            string[] args = Array.Empty<string>();
    
            WebApplication app = Program.Bootstrap(args);
    
            Assert.NotNull(app);
        }
    }
    

    You could then ignore the uncovered code of Main() (as it’s trivial) with [ExcludeFromCodeCoverage]

    This would then give you coverage of most of the method, but how valuable that is other than "chasing code coverage" is a different matter.

    Login or Signup to reply.
  2. When implementing unit tests it is best practise to re=structure your code in ways to facilitate testing. This will include exposing methods that you want to be testable via public interfaces. This in turn will ensure that you only use publicly typed interfaces for the arguments and response types to your methods.

    It is not a common requirement to unit-test the main method, as this test is often better realised by simply running the application. In your case the Main(string[]) method is a void method and as such does not return anything so you should use BeginInvoke instead of Invoke, and not try to Assert any criteria against the output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search