コードをテスト可能にするために、コントローラーの依存関係を抽象化する必要があります。リポジトリパターンを使用してデータ アクセスを抽象化すると非常に便利です。リポジトリをコントローラーに挿入します。
public class LocationController : Controller
{
private ILocationRepository _locationRepository;
public LocationController(ILocationRepository locationRepository)
{
_locationRepository = locationRepository;
}
}
これで、リポジトリをモックできます。Moqフレームワークと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());
そして、このテストに合格するコードを実装できます。
[HttpPost]
public ActionResult Create(Location location)
{
if (ModelState.IsValid)
{
_locationRepository.Add(location);
_locationRepository.Save();
return RedirectToAction("Index");
}
}
リポジトリの実装と MVC アプリケーションのテストの詳細について
は、ASP.NET MVC アプリケーションでのリポジトリと作業単位パターンの実装 を参照してください。リクエストごとに Unit of Workを持つことも素晴らしい機能です。