Pergunta

Here my simplified controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (!ReCaptcha.Validate(Constants.ReCaptchaPrivateKey))
        ModelState.AddModelError("recaptcha", "Incorrect value, enter the text again.");

    if (ModelState.IsValid)
    {
        //Code for register 
    }
}

Where should the data validation logic be tested?

Foi útil?

Solução

I would create an interface for ReCaptcha validation, or for what that represents, which is Human validation really, so something like:

public interface IHumanValidator
{
    ///Checks validates that the currentuser is human and not a bot
    bool Validate();

    /// Returns the text to display if the validation fails
    string ValidationFailText{get;}
}

You would need to change the controller to accept an IHumanValidator in the constructor (or a property if you must). Then change you method to:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (!m_humanValidator.Validate())
        ModelState.AddModelError("recaptcha", m_humanValidator.ValidationFailText);

    if (ModelState.IsValid)
    {
        //Code for register 
    }
}

Then I would inject an implementation which is based on the ReCaptcha validation into the controller and validate against that:

public class ReCaptchaHumanValidator : IHumanValidator
{
    public bool Validate()
    {
        ReCaptcha.Validate(Constants.ReCaptchaPrivateKey)
    }

    public string ValidationFailText
    {
        get{return "Incorrect value, enter the text again.";}
    }
}

Then you could inject a mock validator for testing which you could configure to return valid or not depending on the test.

This also has the advantage that if you decide to change to another form of validation rather than ReCaptcha then you only need to provide another implementation of IHumanValidator and don't need to change anything else in your code.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top