如何在MVC中对Create方法执行单元测试? [英] How to perform Unit Testing on Create method in MVC?
问题描述
如何在MVC应用程序上执行单元测试?
How to perform a Unit testing on MVC application?
我已经创建了控制器位置. 它具有LocationName,Area,City,PinCode之类的属性.
I have created the Controller Location. It has properties like LocationName,Area,City,PinCode.
现在,我想执行单元测试以检查Location是否保存在DB中. 如何检查.
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....
我想知道如何执行MVC的Create方法的单元测试
I would like to know how to perform the Unit testing of Create method of MVC
我有类似下面的代码
[HttpPost]
public ActionResult Create(Location location)
{
if (ModelState.IsValid)
{
db.Locations.Add(location);
db.SaveChanges();
return RedirectToAction("Index");
}
}
推荐答案
为了使您的代码可测试,您应该抽象控制器的依赖项.使用存储库模式来抽象数据访问非常方便. 注入将您的存储库放入控制器:
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;
}
}
现在您可以模拟您的存储库了.这是使用 Moq 框架和
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");
}
}
您可以在此处阅读有关实现存储库和测试MVC应用程序的更多信息: 每个请求的工作单元.
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.
这篇关于如何在MVC中对Create方法执行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!