我正在使用带有 NUnit 的 Sharp Architechture 和 Rhino Mocks。
我有一个看起来像这样的测试服务
public class TestService : ITestService {
public TestService(ITestQueries testQueries, IRepository<Test> testRepository,
IApplicationCachedListService applicationCachedListService) {
Check.Require(testQueries != null, "testQueries may not be null");
Check.Require(applicationCachedListService != null, "applicationCachedListService may not be null");
_testQueries = testQueries;
_testRepository = testRepository;
_applicationCachedListService = applicationCachedListService;
}
然后我在我的服务中有这个方法
public string Create(TestFormViewModel viewModel, ViewDataDictionary viewData, TempDataDictionary tempData) {
if (!viewData.ModelState.IsValid) {
tempData.SafeAdd(viewModel);
return "Create";
}
try {
var test = new Test();
UpdateFromViewModel(test, viewModel);
_testRepository.SaveOrUpdate(test);
tempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()]
= string.Format("Successfully created product '{0}'", test.TestName);
}
catch (Exception ex) {
_testRepository.DbContext.RollbackTransaction();
tempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()]
= string.Format("An error occurred creating the product: {0}", ex.Message);
return "Create";
}
return "Index";
}
}
然后我有一个看起来像这样的控制器:
[ValidateAntiForgeryToken]
[Transaction]
[AcceptVerbs(HttpVerbs.Post)]
[ModelStateToTempData]
public ActionResult Create(TestFormViewModel viewModel) {
return RedirectToAction(_testService.Create(viewModel, ViewData, TempData));
}
我想编写一个简单的测试,看看何时 !viewData.ModelState.IsValid 我返回“创建”。
到目前为止我有这个但很困惑,因为它真的没有测试控制器它只是在做我告诉它在返回时做的事情。
[Test]
public void CreateResult_RedirectsToActionCreate_WhenModelStateIsInvalid(){
// Arrange
var viewModel = new TestFormViewModel();
_controller.ViewData.ModelState.Clear();
_controller.ModelState.AddModelError("Name", "Please enter a name");
_testService.Stub(a => a.Create(viewModel, new ViewDataDictionary(), new TempDataDictionary())).IgnoreArguments().Return("Create");
// Act
var result = _controller.Create(viewModel);
// Assert
result.AssertActionRedirect().ToAction("Create"); //this is really not testing the controller??.
}
任何帮助表示赞赏。