Exemplo n.º 1
0
        public async Task CombineAFuncAndAMiddlewareShouldReturnAFuncThatCombinesThemAsync()
        {
            // Given
            var calls = new List <string>();

            AsyncMiddlewareFunc <string, int> func = async(str, _) =>
            {
                calls.Add("Func");
                await Task.CompletedTask;
                return(str.Length);
            };

            AsyncMiddleware <string, int> middleware = async(str, next, ct) =>
            {
                calls.Add("Before");
                var result = await next(str, ct);

                calls.Add("After");
                return(result);
            };

            var context = "Hello world!";

            // When
            var result = await func.Combine(middleware)(context, default);

            // Then
            result.Should().Be(context.Length);
            calls.Should().Equal("Before", "Func", "After");
        }
Exemplo n.º 2
0
        public async Task ComposingMiddlewaresShouldProducesACompositeMiddlewareAsync()
        {
            // Given
            var calls = new List <string>();

            AsyncMiddlewareFunc <string, int> func = async(str, _) =>
            {
                calls.Add("Func");
                await Task.CompletedTask;
                return(str.Length);
            };

            AsyncMiddleware <string, int> MakeMiddleware(int count)
            {
                return(async(str, next, ct) =>
                {
                    calls !.Add("Before" + count);
                    var result = await next(str, ct);

                    calls.Add("After" + count);
                    return result;
                });
            }

            var middleware1 = MakeMiddleware(1);
            var middleware2 = MakeMiddleware(2);
            var middleware3 = MakeMiddleware(3);

            var context = "Hello world!";

            // When
            var middleware = middleware1.Compose(middleware2, middleware3);
            var result     = await func.Combine(middleware)(context, default);

            // Then
            result.Should().Be(context.Length);
            calls.Should().Equal("Before1", "Before2", "Before3", "Func", "After3", "After2", "After1");
        }