1+ #if NET5_0_OR_GREATER
2+ using System . Collections . Immutable ;
3+
4+ namespace Atc . Test . Customizations ;
5+
6+ [ AutoRegister ]
7+ public class ImmutableObjectCustomization : ICustomization
8+ {
9+ public void Customize ( IFixture fixture )
10+ {
11+ fixture . Customizations . Add (
12+ new ImmutableObjectBuilder (
13+ typeof ( ImmutableArray < > ) ,
14+ typeof ( List < > ) ,
15+ o => ImmutableArray . ToImmutableArray ( o ) ) ) ;
16+
17+ fixture . Customizations . Add (
18+ new ImmutableObjectBuilder (
19+ typeof ( ImmutableList < > ) ,
20+ typeof ( List < > ) ,
21+ o => ImmutableList . ToImmutableList ( o ) ) ) ;
22+
23+ fixture . Customizations . Add (
24+ new ImmutableObjectBuilder (
25+ typeof ( ImmutableDictionary < , > ) ,
26+ typeof ( Dictionary < , > ) ,
27+ o => ImmutableDictionary . ToImmutableDictionary ( o ) ) ) ;
28+
29+ fixture . Customizations . Add (
30+ new ImmutableObjectBuilder (
31+ typeof ( ImmutableHashSet < > ) ,
32+ typeof ( HashSet < > ) ,
33+ o => ImmutableHashSet . ToImmutableHashSet ( o ) ) ) ;
34+
35+ fixture . Customizations . Add (
36+ new ImmutableObjectBuilder (
37+ typeof ( ImmutableSortedSet < > ) ,
38+ typeof ( SortedSet < > ) ,
39+ o => ImmutableSortedSet . ToImmutableSortedSet ( o ) ) ) ;
40+
41+ fixture . Customizations . Add (
42+ new ImmutableObjectBuilder (
43+ typeof ( ImmutableSortedDictionary < , > ) ,
44+ typeof ( SortedDictionary < , > ) ,
45+ o => ImmutableSortedDictionary . ToImmutableSortedDictionary ( o ) ) ) ;
46+ }
47+
48+ private sealed class ImmutableObjectBuilder (
49+ Type immutableType ,
50+ Type underlyingType ,
51+ Func < dynamic , object > converter )
52+ : ISpecimenBuilder
53+ {
54+ public object Create ( object request , ISpecimenContext context )
55+ {
56+ if ( GetRequestType ( request ) is { } type
57+ && type . IsGenericType
58+ && type . GetGenericTypeDefinition ( ) == immutableType
59+ && type . GetGenericArguments ( ) is { Length : > 0 } args )
60+ {
61+ var listType = underlyingType . MakeGenericType ( args ) ;
62+ dynamic list = context . Resolve ( listType ) ;
63+
64+ return converter . Invoke ( list ) ;
65+ }
66+
67+ return new NoSpecimen ( ) ;
68+ }
69+
70+ private static Type ? GetRequestType ( object request )
71+ => request switch
72+ {
73+ ParameterInfo pi => pi . ParameterType ,
74+ Type t => t ,
75+ _ => null ,
76+ } ;
77+ }
78+ }
79+ #endif
0 commit comments