2121
2222using System ;
2323using System . Diagnostics ;
24+ using System . Linq ;
25+ using System . Reflection ;
26+
27+ using AutoMapper ;
2428
2529using Patterns . ExceptionHandling ;
2630using Patterns . Testing . Moq ;
@@ -42,6 +46,36 @@ public static string NewKey(this ScenarioContext context)
4246 }
4347 }
4448
49+ public static TObject CreateAndMapValues < TObject > ( this Table table ) where TObject : new ( )
50+ {
51+ var target = new TObject ( ) ;
52+ table . MapValues ( target ) ;
53+ return target ;
54+ }
55+
56+ public static TObject MapValues < TObject > ( this Table table , TObject target )
57+ {
58+ PropertyInfo [ ] properties = target . GetType ( ) . GetProperties ( ) ;
59+
60+ foreach ( TableRow row in table . Rows )
61+ {
62+ string propertyName = row [ "name" ] ;
63+ string propertyValue = row [ "value" ] ;
64+
65+ PropertyInfo property = properties . FirstOrDefault ( item => item . Name == propertyName ) ;
66+
67+ if ( property == null ) continue ;
68+
69+ object actualValue = property . PropertyType != typeof ( string )
70+ ? Mapper . Map ( propertyValue , typeof ( string ) , property . PropertyType )
71+ : propertyValue ;
72+
73+ property . SetValue ( target , actualValue , null ) ;
74+ }
75+
76+ return target ;
77+ }
78+
4579 public static TValue GetValue < TValue > ( this ScenarioContext context , string key = null , Func < TValue > factory = null )
4680 {
4781 key = ResolveKey < TValue > ( key ) ;
@@ -58,6 +92,20 @@ public static TValue GetValue<TValue>(this ScenarioContext context, string key =
5892 return valueExists ? Try . Get ( ( ) => context . Get < TValue > ( key ) , exception => new ExceptionState ( exception , true ) , factory ) : factory ( ) ;
5993 }
6094
95+ public static object GetValue ( this ScenarioContext context , string key , Func < object > factory = null )
96+ {
97+ bool valueExists = context . ContainsKey ( key ) ;
98+
99+ if ( ! valueExists && factory != null )
100+ {
101+ object value = factory ( ) ;
102+ context [ key ] = value ;
103+ return value ;
104+ }
105+
106+ return valueExists ? Try . Get ( ( ) => context [ key ] , exception => new ExceptionState ( exception , true ) ) : null ;
107+ }
108+
61109 public static void SetValue < TValue > ( this ScenarioContext context , TValue instance , string key = null )
62110 {
63111 key = ResolveKey < TValue > ( key ) ;
0 commit comments