开发者

ASP.NET + Moq + Data Annotations + Resource Strings

I am trying to write a unit test for an Action who's model uses Data Annotations to validate the members. I am using Moq as my mocking framework.

When I 'hard-code' the [Required] error message for the property, everything works great. I am able to run my test just fine, and the test results are expected. However, I need to have the error messages coming from a resource file. So instead of doing:

 [Required(ErrorMessage = "First Name is required")]
    public string FirstName
    {
        get;
        set;
    }

I need to do this instead:

 [Required(ErrorMessageResourceName = "Account_FirstNameRequired", ErrorMessageResourceType = typeof(Resources.ModelValidationErrors))]
    public string FirstName
    {
        get;
        set;
    }

When I use the Resource based string, it works fine.. however, when I try to run my test, I get the following error:

Test method MyProject.Tests.Controllers.AdminAccountsTest.AdminAccounts_Create_Calls_Save threw exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Could not load file or assembly 'App_GlobalResources' or one of its dependencies. The system cannot find the file specified.WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusi开发者_如何转开发on!EnableLog].

Admittedly, I am new to using Moq. I have searched and I didn't have much luck in finding any examples of Moq with Data Annotations, let alone Data Annotations with Resource strings. Can someone please tell me what I am doing wrong?


Internally App_GlobalResources relies on an HttpContext which is not available in unit tests. Here's a blog post that talks about this issue. In short:

avoid App_GlobalResources and App_LocalResources (which has its own set of problems) in MVC.

The proposed solution is to move the resource files outside of special resource directories.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜