【发布时间】:2014-04-06 01:30:40
【问题描述】:
我们遵循被动控制器方法,当用户单击提交时,会触发服务器端验证。屏幕上还有许多其他字段需要验证。
我想获得有关以下方法的反馈。
- 可以在 Presenter 中进行验证吗?
- 由于 UI 中有很多字段,
PerformServerValidations()方法越来越大。有什么办法可以重构它。 -
将
PerformServerValidations()声明为公共并返回 IList 的意图是能够对其进行测试。这是一个很好的方法吗?[TestMethod] public void Presenter_PerformServerValidations_ValidateFromCustomerId_ExpectFalseForInvalidNumber() { //creating presenter presenter.View.Stub(x=>x.FromCustomerId).Return("one two three"); var errorCodes = presenter.PerformServerValidations(); Assert.IsTrue(errorCodes.Contains("ERR_InvalidFromCustomerId")); }
Presenter.cs
public void OnSubmit()
{
var serverValidationErrors = PerformServerValidations();
// View.ServerErrors will loop over the list and sets validator's IsValid property to false
this.View.ServerErrors = serverValidationErrors ;
if(!serverValidationErrors.Any())
{
BindCustomers();
}
}
public IList<string> PerformServerValidations()
{
var errorCodes = new List<string>();
int parsedFromCustomerId;
int parsedToCustomerId;
bool isValidFromCustomerId = int.TryParse(this.View.FromCustomerId, out
parsedFromCustomerId);
bool isValidToCustomerId = int.TryParse(this.View.ToCustomerId, out parsedToCustomerId);
if(!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !isValidFromCustomerId)
{
errorCodes.Add("ERR_InvalidFromCustomerId");
}
if(!string.IsNullOrWhiteSpace(this.View.ToCustomerId) && !isValidToCustomerId)
{
errorCodes.Add("ERR_InvalidToCustomerId");
}
if((!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !string.IsNullOrWhiteSpace(this.View.FromCustomerId) && (isValidFromCustomerId && isValidToCustomerId))
{
if(parsedFromCustomerId > parsedToCustomerId)
{
errorCodes.Add("ERR_InvalidCustomerIdRange");
}
}
//There are many other fields to be validated
return errorCodes;
}
【问题讨论】:
标签: c# asp.net validation unit-testing mvp