How to perform Unit Testing on Create method in MV

2019-07-29 04:30发布

问题:

How to perform a Unit testing on MVC application?

I have created the Controller Location. It has properties like LocationName,Area,City,PinCode.

Now, I want to perform unit test to check whether Location saves in DB or not. How to check it.

I have go through tons of videos, every where they just put the Unit test of Mathematical operations like adding,Dividing , subtracting....

I would like to know how to perform the Unit testing of Create method of MVC

I have code something like below

 [HttpPost]
    public ActionResult Create(Location location)
    {
        if (ModelState.IsValid)
        {
            db.Locations.Add(location);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }
    }

回答1:

In order to make your code testable, you should abstract dependencies of controller. It's very handy to use Repository pattern to abstract data access. Inject your repository into controller:

public class LocationController : Controller
{
    private ILocationRepository _locationRepository;

    public LocationController(ILocationRepository locationRepository)
    {
         _locationRepository = locationRepository;
    }
}

Now you can mock your repository. Here is sample test with Moq framework and MvcContrib:

// Arrange
Mock<ILocationRepository> repository = new Mock<ILocationRepository>();
var controller = new LocationController(repository.Object);
Location location = new Location("New York);
// Act
var result = controller.Create(location);
// Assert
result.AssertActionRedirect()
      .ToAction<LocationController>(c => c.Index());
repository.Verify(r => r.Add(location));
repository.Verify(r => r.Save());

And you can implement code, which will pass this test:

[HttpPost]
public ActionResult Create(Location location)
{
    if (ModelState.IsValid)
    {
        _locationRepository.Add(location);
        _locationRepository.Save();
        return RedirectToAction("Index");  
    }
}

You can read more on implementing repositories and testing MVC applications here: Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application. Nice feature also to have Unit of Work per request.