Home | InfoDip | Detour | Kid Stuff | Clippings | Tips | InfoScraper | Tools | Games | Essays | Deals | Kit
Eric Hartwell's InfoWeb
| May 2004 | ||||||
| Sun | Mon | Tue | Wed | Thu | Fri | Sat |
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | 31 | |||||
| Jan Jun | ||||||
Constraints and unit testing.
11:42:05 AM
One thing that I would like to enforce in my unit tests are constraints. Examples of constraints are things like read-only properties and sealed classes. If a developer comes along and removes one of those constraints by making the property read-write, or by unsealing the class, those changes are not detectable by simply recompiling the code.
One way to enforce constraints is to write unit tests that assert their existence. To help folks out, I've written the beginnings of a utility class that can be used with NUnit tests. Here's the source code for that class for folks who are interested. Feedback about these ideas would be greatly appreciated.
Public Class AssertEx : Inherits Assertion Public Shared Sub AssertReadOnlyProperty(ByVal t As Type, ByVal propertyName As String) Dim pi As PropertyInfo = t.GetProperty(propertyName) Assert(String.Format("Read-only property {0} in class {1} cannot be read from", propertyName, t.FullName), pi.CanRead) Assert(String.Format("Read-only property {0} in class {1} can be written to", propertyName, t.FullName), Not pi.CanWrite) End Sub Public Shared Sub AssertWriteOnlyProperty(ByVal t As Type, ByVal propertyName As String) Dim pi As PropertyInfo = t.GetProperty(propertyName) Assert(String.Format("Write-only property {0} in class {1} can be read from", propertyName, t.FullName), Not pi.CanRead) Assert(String.Format("Write-only property {0} in class {1} cannot be written to", propertyName, t.FullName), pi.CanWrite) End Sub ' TODO: Implement a visibility property assert - must be internal for example. need to use GetAccessors() ' and assert visibility based on property get/set method visibility Public Shared Sub AssertNotInheritableClass(ByVal t As Type) Assert(String.Format("Class {0} cannot be derived from", t.FullName), t.IsSealed) End Sub Public Shared Sub AssertNonSerializable(ByVal t As Type) Assert(String.Format("Class {0} cannot be serializable", t.FullName), Not t.IsSerializable) End Sub ' TODO: Assert that a class must be abstract Public Shared Sub AssertNotCreatable(ByVal t As Type) Dim cis() As ConstructorInfo = t.GetConstructors() Dim ci As ConstructorInfo For Each ci In cis Assert(String.Format("Non-private constructor found in a class {0} that must not be creatable", t.FullName), ci.IsPrivate) Next End Sub End Class [iunknown.com]11:42:05 AM