在控制器中使用 ReCaptcha 验证测试代码?
这是我的简化控制器:
[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
}
}
数据验证逻辑应该在哪里测试?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会为 ReCaptcha 验证创建一个接口,或者为它所代表的内容创建一个接口,这实际上是人类验证,所以类似于:
您需要更改控制器以在构造函数(或属性)中接受
IHumanValidator
如果你必须的话)。然后将方法更改为:然后我会将基于 ReCaptcha 验证的实现注入到控制器中并对其进行验证:
然后您可以注入一个模拟验证器进行测试,您可以将其配置为根据测试返回有效或无效。
这还有一个优点,如果您决定更改为另一种形式的验证而不是 ReCaptcha,那么您只需要提供 IHumanValidator 的另一个实现,而无需更改代码中的任何其他内容。
I would create an interface for ReCaptcha validation, or for what that represents, which is Human validation really, so something like:
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:Then I would inject an implementation which is based on the ReCaptcha validation into the controller and validate against that:
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.