-
Notifications
You must be signed in to change notification settings - Fork 10
/
CustomValidatorIntegrationTest.cs
94 lines (80 loc) · 3.09 KB
/
CustomValidatorIntegrationTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using Grpc.AspNetCore.FluentValidation.SampleRpc;
using Grpc.Core;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Xunit;
namespace Grpc.AspNetCore.FluentValidation.Test.Integration
{
public class CustomValidatorIntegrationTest : IClassFixture<WebApplicationFactory<Startup>>
{
public CustomValidatorIntegrationTest(WebApplicationFactory<Startup> factory)
{
_factory = factory
.WithWebHostBuilder(builder => builder.ConfigureTestServices(services =>
{
services.AddValidator<HelloRequestValidator>();
}));
}
private readonly WebApplicationFactory<Startup> _factory;
[Fact]
public async Task Should_ResponseMessage_When_MessageIsValid()
{
// Given
var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel());
// When
await client.SayHelloAsync(new HelloRequest
{
Name = "Not Empty Name"
});
// Then nothing happen.
}
[Fact]
public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty()
{
// Given
var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel());
// When
async Task Action()
{
await client.SayHelloAsync(new HelloRequest {Name = string.Empty});
}
// Then
var rpcException = await Assert.ThrowsAsync<RpcException>(Action);
Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode);
}
[Fact]
public async Task Should_ReturnWithTrailingHeader_When_RequestIsInvalid()
{
// Given
var spyHandler = new VerifierHeaderSpyDelegate();
var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel(spyHandler));
// When
await client.SayHelloAsync(new HelloRequest {Name = string.Empty}).ResponseHeadersAsync;
// Then
var headers = spyHandler.ResponseMessage.Headers;
headers.TryGetValues("grpc-status", out var values);
Assert.Single(values, "3");
Assert.True(headers.Contains("grpc-message"));
}
class VerifierHeaderSpyDelegate : ResponseVersionHandler
{
public HttpResponseMessage ResponseMessage { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
ResponseMessage = await base.SendAsync(request, cancellationToken);
return ResponseMessage;
}
}
public class HelloRequestValidator : AbstractValidator<HelloRequest>
{
public HelloRequestValidator()
{
RuleFor(request => request.Name).NotEmpty();
}
}
}
}