【问题标题】:I am Get starting with unit testing with NUnit, (doesn't run the test) Why?我开始使用 NUnit 进行单元测试,(不运行测试)为什么?
【发布时间】:2020-11-07 17:09:00
【问题描述】:

我开始在 Visual Studio 中使用单元测试。我正在阅读有关它的 Microsoft 文档:Get started with unit testing,但是当我运行时,不运行测试,并显示:程序,由于其保护级别而无法访问。我不知道我现在要做什么。 你能帮忙吗?

这是我的 Hello World 程序

using System;

namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Hello World!");
        }
    }
}

使用 NUnit 进行单元测试

using NUnit.Framework;
using System.IO;
using System;

namespace HelloWorldTests
{
    public class Tests
    {
        private const string Expected = "Hello World!";

        [SetUp]
        public void Setup()
        {
        }
        [Test]
        public void TestMethod1()
        {
            using (var sw = new StringWriter())
            {
                Console.SetOut(sw);
                demo.Program.Main();

                var result = sw.ToString().Trim();
                Assert.AreEqual(Expected, result);
            }
        }
    }
}

错误显示:错误 CS0122:“程序”由于其保护级别 (CS0122) (HelloWorldTests) 而无法访问

【问题讨论】:

    标签: c# visual-studio unit-testing nunit


    【解决方案1】:

    我不太同意其他答案。不要仅仅为了测试目的而公开方法。这可能会破坏封装。

    改为使用InternalsVisibleToAttribute 属性。

    【讨论】:

      【解决方案2】:

      感谢所有cmets,

      using System;
      
      namespace demo
      {
          public class Program
          {
              public static void Main()
              {
      
                  Console.WriteLine("Hello World!");
              }
      
          }
      }
      

      【讨论】:

        【解决方案3】:

        您需要将您的类程序声明为公开的,以便您的测试项目可以访问它。

        【讨论】:

        • 是的,我做到了。现在: Main(string[] args) 由于其保护级别而无法访问。
        • 因此,按照这个逻辑,我建议您也将 main 方法设置为 public。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-02
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        相关资源
        最近更新 更多