我正在开始使用 NUnit 进行单元测试,(不 运行 测试)为什么?
I am Get starting with unit testing with NUnit, (doesn't run the test) Why?
我开始在 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:'Program' 由于其保护级别 (CS0122) (HelloWorldTests) 而无法访问
您需要将您的 class 程序声明为 public 以便您的测试项目可以访问它。
感谢所有评论,
using System;
namespace demo
{
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World!");
}
}
}
我不太同意其他答案。不要仅仅为了测试目的而制作方法 public。这可能会破坏封装。
而是使用 InternalsVisibleToAttribute 属性。
我开始在 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:'Program' 由于其保护级别 (CS0122) (HelloWorldTests) 而无法访问
您需要将您的 class 程序声明为 public 以便您的测试项目可以访问它。
感谢所有评论,
using System;
namespace demo
{
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World!");
}
}
}
我不太同意其他答案。不要仅仅为了测试目的而制作方法 public。这可能会破坏封装。
而是使用 InternalsVisibleToAttribute 属性。