c# - 需要使用 NUnit 测试 Controller HTTP 方法

标签 c# unit-testing nunit

我用简单的 HTTP 方法用 C# 编写了一个后端。获取、发布(创建)、放置(更新)、删除。

现在我想用 NUnit 实现一些单元测试。我找到了 this article其中描述了 NUnit 的基础知识。但现在的问题是,我如何使用它来创建单元测试?

任何人都可以解释我必须做什么来测试 Controller HTTP 方法吗?

提前致谢:)

编辑:

为了清楚起见,我想测试是否可以通过我的 Controller 类获取、创建、更新和删除项目。

最佳答案

假设您使用的是 ASP.NET MVC,您可以这样做:

 public class ProductController : Controller
 {
      public ActionResult Index()
      {
           // Add action logic here
           throw new NotImplementedException();
      }

      public ActionResult Details(int Id)
      {

           return View("Details");
      }
 }


 [TestFixture]
 public class ProductControllerTest
 {
      [Test]
      public void TestDetailsView()
      {
           var controller = new ProductController();
           var result = controller.Details(2) as ViewResult;
           Assert.AreEqual("Details", result.ViewName);

      }
 }

示例取自 https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs

关于c# - 需要使用 NUnit 测试 Controller HTTP 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136056/

相关文章:

unit-testing - 如何对文件管理器类进行单元测试?

c# - 从保存对话框中捕捉取消状态,以获取即将关闭且未保存更改的 MS Word 文档

C# Indexer 属性 - 有什么方法可以虚拟化 get 而不是 set 方法?

C# mvc2 在代码中创建纯文本电子邮件

c# - LINQ to Entities 错误发生在运行时但不在单元测试中

unit-testing - 激活器( Play ) testOnly 运行所有测试;如何真正运行其中的一些?

c#-4.0 - 单元测试代码契约(Contract)

c# - Vs2019 无法运行 NUnit 测试 - 'testhost.x86.exe' 问题

c# - 如何有条件地以不太冗长的方式写出 XML?

unit-testing - CodeIgniter 中的单元测试和功能测试