Skip to content

Commit 11b0cc2

Browse files
committed
add test for creating many-to-many (failing)
1 parent 14d175b commit 11b0cc2

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
1+
using System.Collections.Generic;
2+
using System.Linq;
13
using System.Net;
4+
using System.Net.Http;
5+
using System.Net.Http.Headers;
26
using System.Threading.Tasks;
37
using Bogus;
48
using JsonApiDotNetCore.Serialization;
59
using JsonApiDotNetCoreExample.Data;
610
using JsonApiDotNetCoreExample.Models;
11+
using Microsoft.EntityFrameworkCore;
12+
using Newtonsoft.Json;
713
using Xunit;
14+
using Person = JsonApiDotNetCoreExample.Models.Person;
815

916
namespace JsonApiDotNetCoreExampleTests.Acceptance
1017
{
@@ -52,5 +59,68 @@ public async Task Can_Fetch_Many_To_Many_Through()
5259
var tagResponse = Assert.Single(articleResponse.Tags);
5360
Assert.Equal(tag.Id, tagResponse.Id);
5461
}
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+
}
55125
}
56126
}

0 commit comments

Comments
 (0)