如何为程序编写测试用例。CS代码,没有主方法或内部任何方法?

发布于 2025-02-13 04:54:57 字数 283 浏览 0 评论 0原文

我正在使用.NET 6.0

我的项目中有一个文件: program.cs ,包含用于控制器和服务的注册和映射代码。

像:

builder.Services.AddControllers();
builder.Services.AddServices();

现在,我想编写这些代码行的测试用例,但是在程序中,没有任何方法可以从[事实]方法中调用。甚至不是主要()方法。

有人可以阐明我们如何用测试用例介绍此代码吗?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

再浓的妆也掩不了殇 2025-02-20 04:54:58

在VS2022中创建新的Web应用程序时,有一个复选框“请勿使用顶级语句” 。如果将其放置在program.cs中,则会得到您看到的内容。如果您确实检查了一下,您会得到:

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
        /* Everything exactly as you see in your Program.cs, but indented */
        }
    }
}

因此,如果您设想想要在测试中调用此方法(有点奇怪,但好的),我建议使用此选项,而不是创建单独的方法来从调用program.cs

即使您在项目创建过程中确实错误地弄错了该复选框选项,也希望看到在两种形式之间转换并不棘手,将上述作为模板(并调整名称空间名称)

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)

嘿咻 2025-02-20 04:54:58

遵循以下步骤完成我的代码覆盖范围:

  1. 在新的静态类中为WebApplicationBuilder创建了一个扩展方法。
  2. 将可测试的代码从program.cs移动到扩展方法。
  3. 为扩展方法写了测试用例。

Followed below steps to complete my code coverage:

  1. Created an extension method for WebApplicationBuilder within a new static class.
  2. Moved the testable code from Program.cs to the extension method.
  3. Wrote the test cases for the extension method.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文