gpt4 book ai didi

c# - c#中的单元测试 Controller 方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:05 25 4
gpt4 key购买 nike

我正在尝试对 Controller 方法 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; }
}

然后我有我的 Controller 方法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);
}

最佳答案

当您说要对 Controller 方法进行单元测试时,您是指单元测试还是集成测试?两种测试类型均有效。

对您的 Controller 方法进行单元测试可能会导致几个不同的测试:

* 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

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

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

关于c# - c#中的单元测试 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37610328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com