简体   繁体   中英

Testing Data Annotations using Moq in Entity Framework

Does Moq properly take into account Data Annotations while testing a Mock<DbContext> and Mock<DbSet<IEntity>> ? For instance, will the proper validation exceptions be thrown if I attempt to do something that is expressly forbidden by the Data Annotations of a Code First Entity Model? If not, how can I properly test my expected results from Data Annotations?

edit: I should note that I am using Entity Framework 6, as it has been overhauled to work much better with Mock Frameworks.

The generally accepted wisdom in unit testing is "don't test code you don't own", so in this case even if Moq could do this (and it can't because as mentioned by Ela, it just provides fake implementations of certain parts of an interface) you shouldn't - you have to accept that the DataAnnotations provided by System.ComponentModel (or whichever) have been tested by their author, and work as advertised.

Of course if you have written your own custom attribute then you unit test this annotation validation code in a separate test class that tests its functionality independent of it being stacked onto a property.

Also, given that you have a Mock DbContext and EntitySet , I don't even see where DataAnnotations come into it - they would only be relevant in a unit test for some implementation of an actual entity , in which case you shouldn't be anywhere near a DbContext or EntitySet - you should be manually creating an entity (or mocking one) for the test at hand. Feel free to let us know what the context of these tests are!

Update: In order to have a regression test for the presence of a specific attribute on a specific property, you could use reflection:

public void MyEntityClass_PropertyFoo_HasRequiredAttribute()
{
    var prop = typeof(MyEntity).GetProperties().FirstOrDefault(p=>p.Name=="Foo");
    if (prop!=null)
    {
        object[] attributes = prop.GetCustomAttributes(typeof(RequiredAttribute), true);
        if (attributes.Length==0)
        {
           //someone took it out, explode your test here.
        }
    }
}

I don't think there is any other reliable way to enforce that requirement, but then again I may well be wrong...

Mock only gives you a "faked" object, it does not implement any functionality. It is just to control parts of your code or prevent null pointer exception because certain instances are not set up at all. But all methods which are not specifically set up within a mocked object will not do anything.

There are certain articles of how to unit test entity framework, maybe this helps. For example: http://msdn.microsoft.com/en-us/ff714955.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM