无法进入MVC Custom RequiredAttribute

时间:2013-10-05 14:26:34

标签: c# asp.net-mvc unit-testing debugging visual-studio-2012

我无法进入我的自定义RequiredAttribute。

我已经关注了这篇文章How to: Debug .NET Framework Source

在工具>选项>调试>一般:

我已Enable .NET Framework source stepping勾选

我有Enable Just My Code未经批准的

我已经使用单元测试创​​建了自定义RequiredAttribute的基本示例:

using System.ComponentModel.DataAnnotations;

public class CustomRequiredAttribute : RequiredAttribute
{
    public bool IsValid(object value, object container)
    {
        if (value == null)
        {
            return false;
        }

        string str = value as string;

        if (!string.IsNullOrWhiteSpace(str))
        {
            return true;
        }

        return false;
    }
}

此测试模型使用:

public class CustomRequiredAttributeModel
{
    [CustomRequired]
    public string Name { get; set; }
}

这是单元测试(正确传递断言):

    [Fact]
    public void custom_required_attribute_test()
    {
        // arrange
        var model = new CustomRequiredAttributeModel();
        var controller = AccountController();

        // act
        controller.ValidateModel(model);

        // assert
        Assert.False(controller.ModelState.IsValid);
    }

单元测试使用此辅助方法:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;

public static class ModelHelper
{
    public static void ValidateModel(this Controller controller, object viewModel)
    {
        controller.ModelState.Clear();

        var validationContext = new ValidationContext(viewModel, null, null);
        var validationResults = new List<ValidationResult>();

        Validator.TryValidateObject(viewModel, validationContext, validationResults, true);

        foreach (var result in validationResults)
        {
            if (result.MemberNames.Any())
            {
                foreach (var name in result.MemberNames)
                {
                    controller.ModelState.AddModelError(name, result.ErrorMessage);
                }
            }
            else
            {
                controller.ModelState.AddModelError("", result.ErrorMessage);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在CustomRequiredAttribute中更改您的方法以使用覆盖,

public class CustomRequiredAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }

        string str = value as string;

        if (!string.IsNullOrWhiteSpace(str))
        {
            return true;
        }

        return false;
    }
}