【问题标题】:unit testing controller method in c#c#中的单元测试控制器方法
【发布时间】:2016-06-03 09:09:55
【问题描述】:

我正在尝试对控制器方法create 进行单元测试我想测试数据是否保存到数据库中,我创建了一个名为Person 的模型类,其中我有诸如人名、姓氏、电子邮件和年龄

public class Person
{
    [Key]
    public int PersonID { get; set; }

    [Display(Name = "Name")]
    [Required]
    public string  name { get; set; }

    [Display(Name = "Last Name")]
    [Required]
    public string  lastName { get; set; }

    [Display(Name = "Email")]
    [Required]
    public string  email { get; set; }

    [Display(Name = "Age")]
    [Required]
    public int age { get; set; }
}

然后我有我的控制器方法Create,我想测试它是否保存在数据库中。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PersonID,name,lastName,email,age")] Person person)
{
    if (ModelState.IsValid)
    {
        db.MyPersons.Add(person);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(person);
}

【问题讨论】:

  • 模拟db 并检查是否调用了AddSaveChanges。您没有提供有关单元测试框架的详细信息,因此无法建议实际实施。

标签: c#


【解决方案1】:

当您说要对控制器方法进行单元测试时,您是真的要进行单元测试还是要考虑集成测试?两种测试类型都有效。

对你的控制器方法进行单元测试可能会导致几个不同的测试:

* Check if the posted result matches the Create method (does the binding work)
* Check is the ModelState is valid for a correct post and invalid for an incorrect one
* Check if the person is added to the collection and if the collection is saved (these tests are implementation specific and it looks like you're using an orm framework for this and verifying the orm works is not a task you should perform)
* Check if the correct view is returned with the correct data

顺便说一句,我列出的每个测试用例可能需要多个单元测试。

如果你真的想要一个集成测试,你可能只想检查数据是否被持久化到数据库中。这可能需要您为测试场景进行设置,在该场景中创建一个空数据库,然后通过从数据库中取出数据并检查值来进行验证。请记住,从每个测试的新/空数据库开始是使测试真正相互独立的唯一方法 - 从长远来看,当添加越来越多的测试以及项目变老而您忘记时,这将有助于您其他测试是做什么/如何进行的。

【讨论】:

  • 发布的结果与create方法一致。 ModelState 对正确的帖子有效,人被保存到数据库并返回正确的视图。我基本上想要的是一种对“创建”方法进行单元测试的方法。
  • @user3852419 我不明白?您希望有人为您编写一个包含多个单元测试的类,以便它完全覆盖/测试您的 Create 方法?
  • @user3852419 您希望它内嵌在 SO 上,采用复制/粘贴友好的格式还是指向外部资源/zip 的链接以便于下载?
  • 如何附加 Zip 文件?
猜你喜欢
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2022-07-27
  • 2017-05-08
  • 1970-01-01
相关资源
最近更新 更多