Click here to Skip to main content
15,886,741 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Please see the example.
Say I have the data model as
public class Model
{
    [Required(ErrorMessage = "You must enter a username.")]
    [StringLength(10, MinimumLength = 4,
        ErrorMessage = "The username must be between 4 and 10 characters long")]
    [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "The username must only contain letters (a-z, A-Z).")]
    public string Username { get; set; }
 
    [Required(ErrorMessage = "You must enter a name.")]
    public string Name { get; set; }
}

Now I want to do a unit test on the validation. For example if I input invalid charter then click a save button the screen will display a warning message. The message comes from the validation. My question is that should I do it on ViewModel or Model directly?

How, should I mock the ICommand as well?

What I have tried:

I might do on the ViewModel unit test. Say mock up a ViewModel then mock the property of the Model.
Posted
Updated 22-May-18 22:46pm

1 solution

I googled "unit test mvc model validation" and this was the first result

TDD for ASP.NET MVC Part 4: Unit Testing View Model Validation -- Visual Studio Magazine[^]

If you google yourself you'll find others. In general though you should only unit test your own code, the model validation is Microsoft's code and you should simply assume they have tested it themselves and that it works. Saying that, however, as you have regex validation there probably is still value in testing that your regex is working as expected so unit testing in this case is probably ok to do.
 
Share this answer
 
Comments
Member 12658724 23-May-18 7:32am    
It's not ASP.NET MVC. It's WPF application. View Model in ASP.NET MVC and ViewModel in WPF, they are totally different things.
F-ES Sitecore 23-May-18 7:43am    
I see you missed the take away from my comment. Try googling "unit test wpf model validation".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900