1+ namespace Tests . AttributeTests
2+ {
3+ using System . Collections . Generic ;
4+
5+ using AspNetCoreExample . Attributes ;
6+
7+ using DataDAL . Tables ;
8+
9+ using Microsoft . AspNetCore . Mvc ;
10+ using Microsoft . VisualStudio . TestTools . UnitTesting ;
11+
12+ [ TestClass ]
13+ public class ValidateModelTests : AttributeTestBase
14+ {
15+ private const string ModelKey = "Model" ;
16+
17+ private ValidateModelAttribute attributeToTest ;
18+
19+ [ TestInitialize ]
20+ public override void SetUp ( )
21+ {
22+ base . SetUp ( ) ;
23+ this . attributeToTest = new ValidateModelAttribute ( ) ;
24+ }
25+
26+ [ TestMethod ]
27+ public void ShouldReturnOkIfModelIsValid ( )
28+ {
29+ // Arrange
30+ var model = new User ( ) ;
31+ var requestParameter = this . GetValidateModelAttributeRequestParameters ( model ) ;
32+ var actionExecutingContext = this . CreateActionExecutingContext ( this . Controller , requestParameter ) ;
33+
34+ // Test
35+ this . attributeToTest . OnActionExecuting ( actionExecutingContext ) ;
36+
37+ // Assert
38+ Assert . IsNull ( actionExecutingContext . Result ) ;
39+ }
40+
41+ [ TestMethod ]
42+ public void ShouldReturnBadRequestIfModelIsInvalid ( )
43+ {
44+ // Arrange
45+ const string InvalidModel = "test" ;
46+ var requestParameter = this . GetValidateModelAttributeRequestParameters ( InvalidModel ) ;
47+ var actionExecutingContext = this . CreateActionExecutingContext ( this . Controller , requestParameter ) ;
48+ actionExecutingContext . ModelState . AddModelError ( ModelKey , "Invalid Model" ) ;
49+
50+ // Test
51+ this . attributeToTest . OnActionExecuting ( actionExecutingContext ) ;
52+
53+ // Assert
54+ Assert . IsNotNull ( actionExecutingContext . Result ) ;
55+ Assert . IsInstanceOfType ( actionExecutingContext . Result , typeof ( BadRequestObjectResult ) ) ;
56+ }
57+
58+ [ TestMethod ]
59+ public void ShouldReturnBadRequestIfModelIsNotAvailable ( )
60+ {
61+ // Arrange
62+ const string NotAvailableModel = null ;
63+ var requestParameter = this . GetValidateModelAttributeRequestParameters ( NotAvailableModel ) ;
64+ var actionExecutingContext = this . CreateActionExecutingContext ( this . Controller , requestParameter ) ;
65+
66+ // Test
67+ this . attributeToTest . OnActionExecuting ( actionExecutingContext ) ;
68+
69+ // Assert
70+ Assert . IsNotNull ( actionExecutingContext . Result ) ;
71+ Assert . IsInstanceOfType ( actionExecutingContext . Result , typeof ( BadRequestResult ) ) ;
72+ }
73+
74+ private IDictionary < string , object > GetValidateModelAttributeRequestParameters ( object model )
75+ {
76+ return new Dictionary < string , object > { { ModelKey , model } } ;
77+ }
78+ }
79+ }
0 commit comments