我们遵循被动控制器方法,当用户点击提交时,会触发服务器端验证。屏幕上还有许多其他字段需要验证。
我想获得有关以下方法的反馈。
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;
}
答案 0 :(得分:0)
也许您应该查看人们在这里说的话:.Net object validation frameworks