I am using .Net 6.0
I have a file in my project : Program.cs, containing registration and mapping code for controllers and services.
like:
builder.Services.AddControllers();
builder.Services.AddServices();
Now, I want to write, test cases for these lines of code, but there is no any method to call from the [Fact] method, inside the program.cs. Not even the main() method.
Can somebody please put some light on how can we cover this code with our test cases ?
CodePudding user response:
Followed below steps to complete my code coverage:
- Created an extension method for WebApplicationBuilder within a new static class.
- Moved the testable code from Program.cs to the extension method.
- Wrote the test cases for the extension method.
CodePudding user response:
When you create a new web application in VS2022, there's a checkbox "Do not use top-level statements". If you leave it unchecked, you get what you're seeing in Program.cs
. If you do check it, you'll get:
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
/* Everything exactly as you see in your Program.cs, but indented */
}
}
}
So if you do envisage wanting to call this method in tests (slightly odd, but okay), I'd recommend using this option rather than creating a separate method to call from Program.cs
.
Even if you do get that checkbox option wrong during project creation, you should hopefully see that it's not tricky to transform between the two forms, using the above as a template (and adjusting namespace name)