Created
January 7, 2012 20:53
-
-
Save ianfnelson/1576006 to your computer and use it in GitHub Desktop.
Test Domain Entities Contain Only Virtual Public Members
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// This test is designed to catch those instances where we forget to mark public members on entities | |
/// as virtual - before NH complains at runtime. | |
/// | |
/// Where classes implement properties from interfaces, the CLR will treat those properties | |
/// as virtual even when they have not explicitly been set as such (e.g. implementations of IEntity.Id) | |
/// so this test is not fool-proof. But it should help. | |
/// </summary> | |
[Test] | |
public void Convention_AllDomainEntitiesShouldContainOnlyVirtualMembers() | |
{ | |
var entityTypes = typeof(IEntity).Assembly.GetTypes() | |
.Where(t => | |
typeof(IEntity).IsAssignableFrom(t) && | |
t.IsPublic && | |
t.IsClass); | |
const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly; | |
var nonVirtualMethods = entityTypes | |
.SelectMany(t => t.GetMethods(bindingFlags)) | |
.Where(m => !m.IsVirtual) | |
.Select(m => m.DeclaringType.Name + "." + m.Name); | |
var nonVirtualProperties = entityTypes | |
.SelectMany(t => t.GetProperties(bindingFlags)) | |
.Where(p => !p.GetGetMethod(true).IsVirtual) | |
.Select(p => p.DeclaringType.Name + "." + p.Name); | |
var nonVirtualMembers = nonVirtualMethods.Union(nonVirtualProperties); | |
if (nonVirtualMembers.Any()) | |
{ | |
Assert.Fail(string.Format("Non-virtual members found in entities: \r\n{0}", string.Join("\r\n", nonVirtualMembers.ToArray()))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment