简体   繁体   English

如何对方法进行单元测试以检查其是否保存到数据库?

[英]How to unit test a method to check if it saves to the database?

I need to unit test to check if the Create method saves to the database. 我需要进行单元测试,以检查Create方法是否保存到数据库中。 I know that this method should not be unit tested in a real project. 我知道这种方法不应在实际项目中进行单元测试。 I am doing this just for learning and demonstration purposes in a school project. 我这样做只是为了在学校项目中进行学习和演示。 I know that I have to use mocking objects and some abstract dependencies of the controller as I read in some other answers, but because I just started learning c# this doesn't help me too much. 我知道我在阅读其他答案时必须使用模拟对象和控制器的某些抽象依赖关系,但是由于我刚刚开始学习c#,因此对我没有太大帮助。 Can you please show me a simple solution or some advice. 您能告诉我一个简单的解决方案或一些建议吗? Thanks. 谢谢。

This is the Create method: 这是Create方法:

[HttpPost]
[ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Code,Description")] LocationCode locationCode)
    {
        if (ModelState.IsValid)
        {
            uow.LocationCodeRepository.Insert(locationCode);

            return RedirectToAction("Index");
        }

        return View(locationCode);
    }

This is the LocationCode class from the Model: 这是来自Model的LocationCode类:

using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace BookInventory.Models { public class LocationCode { [Key] public int Id { get; set; } public string Code { get; set; } public string Description { get; set; } public virtual ICollection<Book> Books { get; set; } } }

What I did was to create a little class that creates LocalDB test database for every unit test. 我要做的是创建一个小类,为每个单元测试创​​建LocalDB测试数据库。 It is being initialized in the TestInitialize (which runs before every unit test), and it does the following: 它在TestInitialize中初始化(在每个单元测试之前运行),它执行以下操作:

  1. Check if there is an existing database. 检查是否存在现有数据库。 If yes, delete it. 如果是,请删除它。
  2. Create a new database. 创建一个新的数据库。
  3. Seed it with some test data. 播种一些测试数据。
  4. Run the unit test. 运行单元测试。
  5. Go to the next test, and go back to 1. 转到下一个测试,然后返回到1。

This runs very fast and allows you to really test you queries/ORM as well, instead of just mocking the repository and assuming that everything works (which is very wrong in my opinion, especially if you're writing your own queries instead of using LINQ. Refactoring something may break things very easily with SQL queries). 这运行得非常快,并且还允许您真正地测试查询/ ORM,而不仅仅是模拟存储库并假设一切正常(我认为这是非常错误的,特别是如果您编写自己的查询而不是使用LINQ 。重构某些东西可能很容易用SQL查询破坏事情)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM