1
+ // Copyright (c) .NET Foundation. All rights reserved.
2
+ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
+
4
+ using System . Collections . Generic ;
5
+ using Microsoft . Extensions . DependencyInjection ;
6
+ using Xunit ;
7
+
8
+ namespace Microsoft . Extensions . Options . Tests
9
+ {
10
+ public class OptionsValidationTest
11
+ {
12
+ [ Fact ]
13
+ public void ValidationResultSuccessIfNameMatched ( )
14
+ {
15
+ var services = new ServiceCollection ( ) ;
16
+ services . AddOptions < ComplexOptions > ( )
17
+ . Validate ( o => o . Boolean )
18
+ . Validate ( o => o . Integer > 12 ) ;
19
+
20
+ var sp = services . BuildServiceProvider ( ) ;
21
+
22
+ var validations = sp . GetService < IEnumerable < IValidateOptions < ComplexOptions > > > ( ) ;
23
+ var options = new ComplexOptions
24
+ {
25
+ Boolean = true ,
26
+ Integer = 13
27
+ } ;
28
+ foreach ( var v in validations )
29
+ {
30
+ Assert . True ( v . Validate ( Options . DefaultName , options ) . Succeeded ) ;
31
+ Assert . True ( v . Validate ( "Something" , options ) . Skipped ) ;
32
+ }
33
+ }
34
+
35
+ [ Fact ]
36
+ public void ValidationResultSkippedIfNameNotMatched ( )
37
+ {
38
+ var services = new ServiceCollection ( ) ;
39
+ services . AddOptions < ComplexOptions > ( "Name" )
40
+ . Validate ( o => o . Boolean ) ;
41
+
42
+ var sp = services . BuildServiceProvider ( ) ;
43
+
44
+ var validations = sp . GetService < IEnumerable < IValidateOptions < ComplexOptions > > > ( ) ;
45
+ var options = new ComplexOptions
46
+ {
47
+ Boolean = true ,
48
+ } ;
49
+ foreach ( var v in validations )
50
+ {
51
+ Assert . True ( v . Validate ( Options . DefaultName , options ) . Skipped ) ;
52
+ Assert . True ( v . Validate ( "Name" , options ) . Succeeded ) ;
53
+ }
54
+ }
55
+
56
+ [ Fact ]
57
+ public void ValidationResultFailedOrSkipped ( )
58
+ {
59
+ var services = new ServiceCollection ( ) ;
60
+ services . AddOptions < ComplexOptions > ( "Name" )
61
+ . Validate ( o => o . Boolean ) ;
62
+
63
+ var sp = services . BuildServiceProvider ( ) ;
64
+
65
+ var validations = sp . GetService < IEnumerable < IValidateOptions < ComplexOptions > > > ( ) ;
66
+ var options = new ComplexOptions
67
+ {
68
+ Boolean = false ,
69
+ } ;
70
+ foreach ( var v in validations )
71
+ {
72
+ Assert . True ( v . Validate ( Options . DefaultName , options ) . Skipped ) ;
73
+ Assert . True ( v . Validate ( "Name" , options ) . Failed ) ;
74
+ }
75
+ }
76
+
77
+ }
78
+ }
0 commit comments