1
+ using System . Collections . Generic ;
2
+ using System . Linq ;
1
3
using System . Net ;
4
+ using System . Net . Http ;
5
+ using System . Net . Http . Headers ;
2
6
using System . Threading . Tasks ;
3
7
using Bogus ;
4
8
using JsonApiDotNetCore . Serialization ;
5
9
using JsonApiDotNetCoreExample . Data ;
6
10
using JsonApiDotNetCoreExample . Models ;
11
+ using Microsoft . EntityFrameworkCore ;
12
+ using Newtonsoft . Json ;
7
13
using Xunit ;
14
+ using Person = JsonApiDotNetCoreExample . Models . Person ;
8
15
9
16
namespace JsonApiDotNetCoreExampleTests . Acceptance
10
17
{
@@ -52,5 +59,68 @@ public async Task Can_Fetch_Many_To_Many_Through()
52
59
var tagResponse = Assert . Single ( articleResponse . Tags ) ;
53
60
Assert . Equal ( tag . Id , tagResponse . Id ) ;
54
61
}
62
+
63
+ [ Fact ]
64
+ public async Task Can_Create_Many_To_Many ( )
65
+ {
66
+ // arrange
67
+ var context = _fixture . GetService < AppDbContext > ( ) ;
68
+ var tag = _tagFaker . Generate ( ) ;
69
+ var author = new Person ( ) ;
70
+ context . Tags . Add ( tag ) ;
71
+ context . People . Add ( author ) ;
72
+ await context . SaveChangesAsync ( ) ;
73
+
74
+ var article = _articleFaker . Generate ( ) ;
75
+
76
+ var route = "/api/v1/articles" ;
77
+ var request = new HttpRequestMessage ( new HttpMethod ( "POST" ) , route ) ;
78
+ var content = new
79
+ {
80
+ data = new
81
+ {
82
+ type = "articles" ,
83
+ relationships = new Dictionary < string , dynamic >
84
+ {
85
+ { "author" , new {
86
+ data = new
87
+ {
88
+ type = "people" ,
89
+ id = author . StringId
90
+ }
91
+ } } ,
92
+ { "tags" , new {
93
+ data = new dynamic [ ]
94
+ {
95
+ new {
96
+ type = "tags" ,
97
+ id = tag . StringId
98
+ }
99
+ }
100
+ } }
101
+ }
102
+ }
103
+ } ;
104
+
105
+ request . Content = new StringContent ( JsonConvert . SerializeObject ( content ) ) ;
106
+ request . Content . Headers . ContentType = new MediaTypeHeaderValue ( "application/vnd.api+json" ) ;
107
+
108
+ // act
109
+ var response = await _fixture . Client . SendAsync ( request ) ;
110
+
111
+ // assert
112
+ var body = await response . Content . ReadAsStringAsync ( ) ;
113
+ Assert . True ( HttpStatusCode . Created == response . StatusCode , $ "{ route } returned { response . StatusCode } status code with payload: { body } ") ;
114
+
115
+ var articleResponse = _fixture . GetService < IJsonApiDeSerializer > ( ) . Deserialize < Article > ( body ) ;
116
+ Assert . NotNull ( articleResponse ) ;
117
+
118
+ var persistedArticle = await _fixture . Context . Articles
119
+ . Include ( a => a . ArticleTags )
120
+ . SingleAsync ( a => a . Id == articleResponse . Id ) ;
121
+
122
+ var persistedArticleTag = Assert . Single ( persistedArticle . ArticleTags ) ;
123
+ Assert . Equal ( tag . Id , persistedArticleTag . TagId ) ;
124
+ }
55
125
}
56
126
}
0 commit comments