Unit testing 在控制器中使用ReCaptcha验证测试代码?

Unit testing 在控制器中使用ReCaptcha验证测试代码?,unit-testing,architecture,tdd,recaptcha,mvcrecaptcha,Unit Testing,Architecture,Tdd,Recaptcha,Mvcrecaptcha,这里是我的简化控制器: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Register(RegisterModel model) { if (!ReCaptcha.Validate(Constants.ReCaptchaPrivateKey)) ModelState.AddModelError("recaptcha", "Incorrect value, enter the text again.");

这里是我的简化控制器:

[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 
    }
}

数据验证逻辑应该在哪里进行测试?

我会为ReCaptcha验证创建一个接口,或者为它所代表的内容创建一个接口,这实际上是人工验证,因此类似于:

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;}
}
您需要更改控制器以接受构造函数中的
IHumanValidator
(或者,如果必须的话,也可以是属性)。然后将方法更改为:

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

    if (ModelState.IsValid)
    {
        //Code for register 
    }
}
然后,我将向控制器中注入一个基于ReCaptcha验证的实现,并根据该实现进行验证:

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

    public string ValidationFailText
    {
        get{return "Incorrect value, enter the text again.";}
    }
}
然后,您可以为测试注入一个模拟验证器,您可以将其配置为根据测试返回有效或无效


这还有一个优点,即如果您决定更改为另一种形式的验证而不是ReCaptcha,那么您只需要提供IHumanValidator的另一个实现,而不需要更改代码中的任何其他内容。

我将为ReCaptcha验证或其代表的内容创建一个接口,这实际上是人类的验证,比如:

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;}
}
您需要更改控制器以接受构造函数中的
IHumanValidator
(或者,如果必须的话,也可以是属性)。然后将方法更改为:

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

    if (ModelState.IsValid)
    {
        //Code for register 
    }
}
然后,我将向控制器中注入一个基于ReCaptcha验证的实现,并根据该实现进行验证:

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

    public string ValidationFailText
    {
        get{return "Incorrect value, enter the text again.";}
    }
}
然后,您可以为测试注入一个模拟验证器,您可以将其配置为根据测试返回有效或无效

这还有一个优点,即如果您决定更改为另一种形式的验证而不是ReCaptcha,那么您只需要提供IHumanValidator的另一个实现,而不需要更改代码中的任何其他内容