我正在使用Sharp Architechture和Rhino Mocks和NUnit。
我有一个看起来像这样的测试服务
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我返回“Create”。
到目前为止,我有这个但是很困惑,因为它确实没有测试控制器它正在做我告诉它在返回时做的事情。
[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??.
}
感谢任何帮助。
答案 0 :(得分:0)
看起来你试着写不是单元测试。它更像是集成测试。遵循单元测试意识形态,您有两个单位:Service
和Controller
。我们的想法是,您应该单独测试每个单元并保持测试简单。首先,你应该为TestService
编写测试。之后,当您覆盖它时,使用Stubs / Mocks为Controller
编写TestService
的测试。因此,您对Controller
的测试看起来是正确的,它会根据Service.Create
方法的结果测试重定向。您应该在没有控制器上下文的情况下为TestService
添加测试,并且它的覆盖范围很广。
如果你想一起测试这些单元,那么你不能使用模拟,它更像是集成测试。
此外,为了覆盖模块之间的集成,您可以使用WatiN或Selenium等工具编写基于Web的测试,以测试整个应用程序。
但无论如何,对单独部件进行单元测试是一种很好的做法。