- Imports System.Reflection
- Imports System.Linq.Expressions
- Imports System.Runtime.CompilerServices
- Imports Rhino.Mocks
- Public Module VisualBasicTestExtensions
- Private Const DefaultFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic
- <Extension()> _
- Public Function [Call](Of T)(ByVal source As T, ByVal method As Action) As T
- method()
- Return source
- End Function
- <Extension()> _
- Public Function [Call](Of T, T1)(ByVal source As T, ByVal method As Action(Of T1), ByVal arg As T1) As T
- method(arg)
- Return source
- End Function
- <Extension()> _
- Public Function [Call](Of T, T1, T2)(ByVal source As T, ByVal method As Action(Of T1, T2), ByVal arg1 As T1, ByVal arg2 As T2) As T
- method(arg1, arg2)
- Return source
- End Function
- <Extension()> _
- Public Function [Call](Of T, T1, T2, T3)(ByVal source As T, ByVal method As Action(Of T1, T2, T3), ByVal arg1 As T1, ByVal arg2 As T2, ByVal arg3 As T3) As T
- method(arg1, arg2, arg3)
- Return source
- End Function
- <Extension()> _
- Public Function [Call](Of T, T1, T2, T3, T4)(ByVal source As T, ByVal method As Action(Of T1, T2, T3, T4), ByVal arg1 As T1, ByVal arg2 As T2, ByVal arg3 As T3, ByVal arg4 As T4) As T
- method(arg1, arg2, arg3, arg4)
- Return source
- End Function
- <Extension()> _
- Public Function AssertWasSet(Of T As Class, TValue)(ByVal source As T, ByVal prop As Expression(Of Func(Of T, TValue)), ByVal value As TValue) As T
- source.AssertWasCalled(Function(c) c.Set(Of TValue)(prop, value))
- Return source
- End Function
- <Extension()> _
- Public Function [Set](Of T As Class, TValue)(ByVal source As T, ByVal expression As Expression(Of Func(Of T, TValue)), ByVal value As TValue) As T
- Dim memberName = CType(expression.Body, MemberExpression).Member.Name
- If (SetProperty(source, memberName, value)) Then Return source
- If (SetField(source, memberName, value)) Then Return source
- Return source
- End Function
- Private Function SetProperty(Of T As Class, TValue)(ByVal source As T, ByVal memberName As String, ByVal value As TValue) As Boolean
- Dim prop = source.GetType().GetProperty(memberName, DefaultFlags)
- If (prop Is Nothing) Then Return False
- If (prop.GetSetMethod Is Nothing) Then Return False
- prop.SetValue(source, value, Nothing)
- Return True
- End Function
- Private Function SetField(Of T As Class, TValue)(ByVal source As T, ByVal memberName As String, ByVal value As TValue) As Boolean
- Dim field = source.GetType().GetField("_" + memberName, DefaultFlags)
- If (field Is Nothing) Then
- field = source.GetType().GetField("_" & Char.ToLower(memberName(0)) & memberName.Substring(1), DefaultFlags)
- End If
- If (field Is Nothing) Then Return False
- field.SetValue(source, value)
- Return True
- End Function
- End Module