简体   繁体   English

单元测试一种通过选择C#进行发布和删除的方法

[英]Unit testing a method which Posts and Deletes by selection C#

I have this method which selects one row of a table and copies it to the another table and then it just deletes it from the first one. 我有这种方法,它选择一个表的一行并将其复制到另一表,然后将其从第一个表中删除。 The problem is that how can I unit test it because it executes two methods (Post and Delete) at the same time. 问题在于我如何对其进行单元测试,因为它同时执行两个方法(发布和删除)。

Here is the method: 方法如下:

public ActionResult Pay(int id, Car car)
    {
        try
        {
            using (BookCarDBEntities db = new BookCarDBEntities())
            {

                var carToDelete = db.Cars.FirstOrDefault(c => c.Id == id);
                var book = CreateNewBooking(carToDelete);
                db.Bookings.Add(book);



                db.Cars.Remove(carToDelete);

                db.SaveChanges();


                return RedirectToAction("ListBookings", "Home");
            }

        }
        catch (Exception ex)
        {
            return View(ex + "error");
        }
    }

    private Booking CreateNewBooking(Car car)
    {
        var bookingCreated = new Booking
        {
            id = car.Id,
            model = car.model,
            make = car.make,
            price = car.price,
            location = car.location
        };

        return bookingCreated;
    }

It does not matter how many external function calls your method to have. 您的方法有多少个外部函数调用无关紧要。 To get the values from the method calls in your method (that you wanna unit test), you should mock those methods to return certain responses when called with certain parameters. 要从方法中的方法调用(您要进行单元测试)中获取值,应模拟这些方法以在使用某些参数调用时返回某些响应。

You should check Moq to learn how to mock methods. 您应检查Moq,以了解如何模拟方法。 Also, I suggest you wrap your methods with an interface (BookCarDBEntities). 另外,我建议您使用接口(BookCarDBEntities)包装方法。 It is more important to write code to testable rather than writing tests to unmanageable code. 将代码编写为可测试代码比将测试编写为难以管理的代码更为重要。 Hope this helps. 希望这可以帮助。

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

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