Skip to content

Commit 849af1f

Browse files
author
hristo.h
committed
Tests & Fixed Builder Implementation (#178)
1 parent 94f9a35 commit 849af1f

File tree

2 files changed

+71
-2
lines changed

2 files changed

+71
-2
lines changed

src/MyTested.AspNetCore.Mvc.ModelState/Builders/Models/ModelStateBuilder.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,18 @@ public IAndModelStateBuilder WithErrors(IDictionary<string, string> errors)
4141

4242
/// <inheritdoc />
4343
public IAndModelStateBuilder WithErrors(object errors)
44-
=> this.WithErrors(new RouteValueDictionary(errors));
44+
{
45+
var errorsAsDictionary = new RouteValueDictionary(errors);
46+
errorsAsDictionary
47+
.ForEach(err => this.AddError(err.Key, err.Value.ToString()));
4548

49+
return this;
50+
}
51+
4652
/// <inheritdoc />
4753
public IModelStateBuilder AndAlso() => this;
4854

49-
private void AddError(string key, string errorMessage) => this.ModelState.AddModelError(key, errorMessage);
55+
private void AddError(string key, string errorMessage)
56+
=> this.ModelState.AddModelError(key, errorMessage);
5057
}
5158
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
namespace MyTested.AspNetCore.Mvc.Test.BuildersTests.ModelsTests
2+
{
3+
using Setups;
4+
using Setups.Controllers;
5+
using Xunit;
6+
using System.Collections.Generic;
7+
8+
public class ModelStateBuilderTests
9+
{
10+
[Fact]
11+
public void WithModelStateWithErrorShouldWorkCorrectly()
12+
{
13+
var requestBody = TestObjectFactory.GetValidRequestModel();
14+
15+
MyController<MvcController>
16+
.Instance()
17+
.WithModelState(modelState => modelState
18+
.WithError("TestError", "Invalid value"))
19+
.Calling(c => c.BadRequestWithModelState(requestBody))
20+
.ShouldReturn()
21+
.BadRequest();
22+
}
23+
24+
[Fact]
25+
public void WithModelStateWithErrorsDictionaryShouldWorkCorrectly()
26+
{
27+
var requestBody = TestObjectFactory.GetValidRequestModel();
28+
var errorsDictionary = new Dictionary<string, string>()
29+
{
30+
["First"] = "SomeError",
31+
["Second"] = "AnotherError",
32+
};
33+
34+
MyController<MvcController>
35+
.Instance()
36+
.WithModelState(modelState => modelState
37+
.WithErrors(errorsDictionary))
38+
.Calling(c => c.BadRequestWithModelState(requestBody))
39+
.ShouldReturn()
40+
.BadRequest();
41+
}
42+
43+
[Fact]
44+
public void WithModelStateWithErrorsObjectShouldWorkCorrectly()
45+
{
46+
var requestBody = TestObjectFactory.GetValidRequestModel();
47+
var errorsObjcet = new
48+
{
49+
First = "SomeError",
50+
Second = "AnotherError",
51+
};
52+
53+
MyController<MvcController>
54+
.Instance()
55+
.WithModelState(modelState => modelState
56+
.WithErrors(errorsObjcet))
57+
.Calling(c => c.BadRequestWithModelState(requestBody))
58+
.ShouldReturn()
59+
.BadRequest();
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)