Xunit.Assert.Throws(string, System.Func)

Here are the examples of the csharp api Xunit.Assert.Throws(string, System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

817 Examples 7

19 Source : ItemUpdatedTests.cs
with Microsoft Public License
from achimismaili

[Fact]
        public void ItemMustNotBeNull()
        {

            // Arrange
            Location l = null;
            // Act

            Action act = () => new Core.Messages.Completed.ItemUpdated<Location>(Guid.NewGuid(), l);

            // replacedert
            replacedert.Throws<ArgumentNullException>(act);

        }

19 Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet

[Fact]
      public void ApplyFiltering_ParenthesisQueryWithoutEscapeShouldThrowException()
      {
         var gq = new GridifyQuery { Filter = @"name=(LI,AM)" };
         Action act = () => _fakeRepository.AsQueryable()
            .ApplyFiltering(gq);

         replacedert.Throws<GridifyFilteringException>(act);
      }

19 Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet

[Fact]
      public void ApplyFiltering_InvalidFilterExpressionShouldThrowException()
      {
         var gq = new GridifyQuery { Filter = "=guid,d=" };
         replacedert.Throws<GridifyFilteringException>(() =>
            _fakeRepository.AsQueryable().ApplyFiltering(gq).ToList());
      }

19 Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet

[Fact]
      public void ApplyFiltering_InvalidCharacterShouldThrowException()
      {
         var gq = new GridifyQuery { Filter = "@name=ali" };
         replacedert.Throws<GridifyFilteringException>(() =>
            _fakeRepository.AsQueryable().ApplyFiltering(gq).ToList());
      }

19 Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet

[Fact] // issue #34
      public void ApplyFiltering_UnmappedFields_ShouldThrowException()
      {
         var gm = new GridifyMapper<TestClreplaced>()
            .AddMap("Id", q => q.Id);

         var exp = replacedert.Throws<GridifyMapperException>(() => _fakeRepository.AsQueryable().ApplyFiltering("name=John,id>0", gm).ToList());
         replacedert.Equal("Mapping 'name' not found",exp.Message); 
      }

19 Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet

[Fact] // issue #34
      public void ApplyOrdering_UnmappedFields_ShouldThrowException()
      {
         var gm = new GridifyMapper<TestClreplaced>()
            .AddMap("Id", q => q.Id);

         var exp = replacedert.Throws<GridifyMapperException>(() => _fakeRepository.AsQueryable().ApplyOrdering("name,id", gm).ToList());
         replacedert.Equal("Mapping 'name' not found",exp.Message); 
      }

19 Source : GridifyMapperShould.cs
with MIT License
from alirezanet

[Fact]
      public void AddMap_DuplicateKey_ShouldThrowErrorIfOverrideIfExistsIsFalse()
      {
         //arrange
         _sut.AddMap("Test", q => q.Name);
         //act
         Action act = () => _sut.AddMap("test", q => q.Name, overrideIfExists: false);
         //replacedert
         var exception = replacedert.Throws<GridifyMapperException>(act);
         //The thrown exception can be used for even more detailed replacedertions.
         replacedert.Equal("Duplicate Key. the 'test' key already exists", exception.Message);
      }

19 Source : GridifyEntityFrameworkSqlTests.cs
with MIT License
from alirezanet

[Fact]
      public void ApplyFiltering_GreaterThanBetweenTwoStringsInEF_SqlServerProvider_ShouldThrowErrorWhenCompatibilityLayerIsDisabled()
      {
         GridifyGlobalConfiguration.DisableEnreplacedyFrameworkCompatibilityLayer();
         replacedert.Throws<InvalidOperationException>(() => _dbContext.Users.ApplyFiltering("name > h").ToQueryString());
      }

19 Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureADBearer_ThrowsWhenBearerSchemeIsAlreadyInUse()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureADBearer(o => { })
                .AddAzureADBearer("Custom", AzureADDefaults.JwtBearerAuthenticationScheme, o => { });

            var provider = services.BuildServiceProvider();
            var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();

            var expectedMessage = $"The JSON Web Token Bearer scheme 'AzureADJwtBearer' can't be replacedociated with the Azure Active Directory scheme 'Custom'. " +
                "The JSON Web Token Bearer scheme 'AzureADJwtBearer' is already mapped to the Azure Active Directory scheme 'AzureADBearer'";

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));

            replacedert.Equal(expectedMessage, exception.Message);
        }

19 Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureADB2C_ThrowsForDuplicatedSchemes()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureADB2C(o => { })
                .AddAzureADB2C(o => { });

            var provider = services.BuildServiceProvider();
            var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));

            replacedert.Equal("A scheme with the name 'AzureADB2C' was already added.", exception.Message);
        }

19 Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureADB2C_ThrowsWhenOpenIdSchemeIsAlreadyInUse()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureADB2C(o => { })
                .AddAzureADB2C("Custom", AzureADB2CDefaults.OpenIdScheme, "Cookie", null, o => { });

            var provider = services.BuildServiceProvider();
            var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();

            var expectedMessage = $"The Open ID Connect scheme 'AzureADB2COpenID' can't be replacedociated with the Azure Active Directory B2C scheme 'Custom'. " +
                "The Open ID Connect scheme 'AzureADB2COpenID' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2C'";

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));

            replacedert.Equal(expectedMessage, exception.Message);
        }

19 Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureADB2C_ThrowsWhenCookieSchemeIsAlreadyInUse()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureADB2C(o => { })
                .AddAzureADB2C("Custom", "OpenID", AzureADB2CDefaults.CookieScheme, null, o => { });

            var provider = services.BuildServiceProvider();
            var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();

            var expectedMessage = $"The cookie scheme 'AzureADB2CCookie' can't be replacedociated with the Azure Active Directory B2C scheme 'Custom'. " +
                "The cookie scheme 'AzureADB2CCookie' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2C'";

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));

            replacedert.Equal(expectedMessage, exception.Message);
        }

19 Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureADB2CBearer_ThrowsForDuplicatedSchemes()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureADB2CBearer(o => { })
                .AddAzureADB2CBearer(o => { });

            var provider = services.BuildServiceProvider();
            var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));

            replacedert.Equal("A scheme with the name 'AzureADB2CBearer' was already added.", exception.Message);
        }

19 Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureADB2CBearer_ThrowsWhenBearerSchemeIsAlreadyInUse()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureADB2CBearer(o => { })
                .AddAzureADB2CBearer("Custom", AzureADB2CDefaults.JwtBearerAuthenticationScheme, o => { });

            var provider = services.BuildServiceProvider();
            var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();

            var expectedMessage = $"The JSON Web Token Bearer scheme 'AzureADB2CJwtBearer' can't be replacedociated with the Azure Active Directory B2C scheme 'Custom'. " +
                "The JSON Web Token Bearer scheme 'AzureADB2CJwtBearer' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2CBearer'";

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));

            replacedert.Equal(expectedMessage, exception.Message);
        }

19 Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureAD_ThrowsForDuplicatedSchemes()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureAD(o => { })
                .AddAzureAD(o => { });

            var provider = services.BuildServiceProvider();
            var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));

            replacedert.Equal("A scheme with the name 'AzureAD' was already added.", exception.Message);
        }

19 Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureAD_ThrowsWhenOpenIdSchemeIsAlreadyInUse()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureAD(o => { })
                .AddAzureAD("Custom", AzureADDefaults.OpenIdScheme, "Cookie", null, o => { });

            var provider = services.BuildServiceProvider();
            var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();

            var expectedMessage = $"The Open ID Connect scheme 'AzureADOpenID' can't be replacedociated with the Azure Active Directory scheme 'Custom'. " +
                "The Open ID Connect scheme 'AzureADOpenID' is already mapped to the Azure Active Directory scheme 'AzureAD'";

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));

            replacedert.Equal(expectedMessage, exception.Message);
        }

19 Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureAD_ThrowsWhenCookieSchemeIsAlreadyInUse()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureAD(o => { })
                .AddAzureAD("Custom", "OpenID", AzureADDefaults.CookieScheme, null, o => { });

            var provider = services.BuildServiceProvider();
            var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();

            var expectedMessage = $"The cookie scheme 'AzureADCookie' can't be replacedociated with the Azure Active Directory scheme 'Custom'. " +
                "The cookie scheme 'AzureADCookie' is already mapped to the Azure Active Directory scheme 'AzureAD'";

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));

            replacedert.Equal(expectedMessage, exception.Message);
        }

19 Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AddAzureADBearer_ThrowsForDuplicatedSchemes()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());

            services.AddAuthentication()
                .AddAzureADBearer(o => { })
                .AddAzureADBearer(o => { });

            var provider = services.BuildServiceProvider();
            var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();

            // Act & replacedert
            var exception = replacedert.Throws<InvalidOperationException>(
                () => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));

            replacedert.Equal("A scheme with the name 'AzureADBearer' was already added.", exception.Message);
        }

19 Source : ConfigurationMethodNotFoundTest.cs
with Apache License 2.0
from aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.IIS)]
        [InlineData(HostType.HttpListener)]
        public void ConfigurationMethodNotFound(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var expectedExceptionType = typeof(EntryPointNotFoundException);
                if (hostType != HostType.IIS)
                {
                    replacedert.Throws(expectedExceptionType, () => deployer.Deploy<ConfigurationMethodNotFoundTest>(hostType));
                }
                else
                {
                    string applicationUrl = deployer.Deploy<ConfigurationMethodNotFoundTest>(hostType);
                    replacedert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl).Contains(expectedExceptionType.Name), "Fatal error not thrown without Configuration method");
                }
            }
        }

19 Source : InvalidConfigurationMethodSignatureTest.cs
with Apache License 2.0
from aspnet

[Theory, Trait("FunctionalTests", "General")]
        [InlineData(HostType.IIS)]
        [InlineData(HostType.HttpListener)]
        public void InvalidConfigurationMethodSignature(HostType hostType)
        {
            var expectedExceptionType = typeof(EntryPointNotFoundException);
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                if (hostType != HostType.IIS)
                {
                    replacedert.Throws(expectedExceptionType, () => deployer.Deploy<InvalidConfigurationMethodSignatureTest>(hostType));
                }
                else
                {
                    string applicationUrl = deployer.Deploy<InvalidConfigurationMethodSignatureTest>(hostType);
                    replacedert.True(HttpClientUtility.GetResponseTextFromUrl(applicationUrl).Contains(expectedExceptionType.Name), "Fatal error not thrown with invalid Configuration method signature");
                }
            }
        }

19 Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void BodyDelegate_ThrowsAsync_ConnectionClosed()
        {
            bool callCancelled = false;

            OwinHttpListener listener = CreateServer(
                env =>
                {
                    GetCallCancelled(env).Register(() => callCancelled = true);
                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
                    responseHeaders.Add("Content-Length", new string[] { "10" });

                    var responseStream = env.Get<Stream>("owin.ResponseBody");
                    responseStream.WriteByte(0xFF);

                    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
                    tcs.TrySetException(new NotImplementedException());
                    return tcs.Task;
                },
                HttpServerAddress);

            try
            {
                replacedert.Throws<AggregateException>(() => SendGetRequest(listener, HttpClientAddress).Result);
            }
            finally
            {
                replacedert.True(callCancelled);
            }
        }

19 Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void Disconnect_ClientDisconnects_EventFires()
        {
            var requestReceived = new ManualResetEvent(false);
            var requestCanceled = new ManualResetEvent(false);

            OwinHttpListener listener = CreateServer(
                async env =>
                {
                    GetCallCancelled(env).Register(() => requestCanceled.Set());
                    requestReceived.Set();
                    replacedert.True(requestCanceled.WaitOne(1000));
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                var requestTask = client.GetAsync(HttpClientAddress);
                replacedert.True(requestReceived.WaitOne(1000));
                client.CancelPendingRequests();
                replacedert.True(requestCanceled.WaitOne(1000));
                replacedert.Throws<AggregateException>(() => requestTask.Result);
            }
        }

19 Source : ExceptionsTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        [InlineData("Microsoft.Owin.Host.HttpListener")]
        public async Task SyncExceptionAfterHeaders(string serverName)
        {
            int port = RunWebServer(
                serverName,
                SyncExceptionAfterHeadersApp);

            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
            replacedert.True(response.IsSuccessStatusCode);
            Stream body = response.Content.ReadreplacedtreamAsync().Result;
            int read = body.Read(new byte[11], 0, 11);
            replacedert.Equal(11, read);
            replacedert.Throws<IOException>(() => body.Read(new byte[10], 0, 10));
        }

19 Source : ExceptionsTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        [InlineData("Microsoft.Owin.Host.HttpListener")]
        public async Task AsyncExceptionAfterHeaders(string serverName)
        {
            int port = RunWebServer(
                serverName,
                AsyncExceptionAfterHeadersApp);

            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
            replacedert.True(response.IsSuccessStatusCode);
            Stream body = response.Content.ReadreplacedtreamAsync().Result;
            int read = body.Read(new byte[11], 0, 11);
            replacedert.Equal(11, read);
            replacedert.Throws<IOException>(() =>
            {
                read = body.Read(new byte[10], 0, 10);
                replacedert.Equal(-1, read);
            });
        }

19 Source : ExceptionsTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [InlineData("Microsoft.Owin.Host.SystemWeb")]
        [InlineData("Microsoft.Owin.Host.HttpListener")]
        public async Task ExceptionAfterHeadersWithContentLength(string serverName)
        {
            int port = RunWebServer(
                serverName,
                ExceptionAfterHeadersWithContentLengthApp);

            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
            replacedert.True(response.IsSuccessStatusCode);
            replacedert.Equal(20, response.Content.Headers.ContentLength.Value);
            Stream body = response.Content.ReadreplacedtreamAsync().Result;
            int read = body.Read(new byte[11], 0, 11);
            replacedert.Equal(11, read);
            replacedert.Throws<IOException>(() => body.Read(new byte[10], 0, 10));
        }

19 Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void Disconnect_ClientDisconnects_Before_CancellationToken_Created()
        {
            var requestReceived = new ManualResetEvent(false);
            var requestCanceled = new ManualResetEvent(false);

            var clientDisposed = new ManualResetEvent(false);

            OwinHttpListener listener = CreateServer(
                env =>
                {
                    requestReceived.Set();

                    // lets wait for client to be gone
                    replacedert.True(clientDisposed.WaitOne(1000));

                    // the most important part is not to observe CancellationToken before client disconnects

                    GetCallCancelled(env).Register(() => requestCanceled.Set());
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new HttpClient())
                {
                    var requestTask = client.GetAsync(HttpClientAddress);
                    replacedert.True(requestReceived.WaitOne(1000));
                    client.CancelPendingRequests();

                    replacedert.Throws<AggregateException>(() => requestTask.Result);
                }

                clientDisposed.Set();

                replacedert.True(requestCanceled.WaitOne(1000));
            }
        }

19 Source : SendFileResponseExtensionsTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void SendFileWhenNotSupported()
        {
            IOwinResponse response = new OwinResponse();
            replacedert.Throws<NotSupportedException>(() => response.SendFileAsync("foo"));
        }

19 Source : TestServerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task Disposed()
        {
            TestServer server = TestServer.Create(app =>
            {
                // Disposes the stream.
                app.UseWelcomePage();
            });

            HttpResponseMessage result = await server.HttpClient.GetAsync("/");
            replacedert.Equal(HttpStatusCode.OK, result.StatusCode);
            server.Dispose();
            AggregateException ex = replacedert.Throws<AggregateException>(() => server.HttpClient.GetAsync("/").Result);
            replacedert.IsType<ObjectDisposedException>(ex.GetBaseException());
        }

19 Source : MapPathMiddlewareTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void ChainedRoutes_Success()
        {
            IAppBuilder builder = new AppBuilder();
            builder.Map("/route1", map =>
            {
                map.Map((string)"/subroute1", UseSuccess);
                map.Run(NotImplemented);
            });
            builder.Map("/route2/subroute2", UseSuccess);
            var app = builder.Build<OwinMiddleware>();

            IOwinContext context = CreateRequest(string.Empty, "/route1");
            replacedert.Throws<AggregateException>(() => app.Invoke(context).Wait());

            context = CreateRequest(string.Empty, "/route1/subroute1");
            app.Invoke(context);
            replacedert.Equal(200, context.Response.StatusCode);
            replacedert.Equal(string.Empty, context.Request.PathBase.Value);
            replacedert.Equal("/route1/subroute1", context.Request.Path.Value);

            context = CreateRequest(string.Empty, "/route2");
            app.Invoke(context);
            replacedert.Equal(404, context.Response.StatusCode);
            replacedert.Equal(string.Empty, context.Request.PathBase.Value);
            replacedert.Equal("/route2", context.Request.Path.Value);

            context = CreateRequest(string.Empty, "/route2/subroute2");
            app.Invoke(context);
            replacedert.Equal(200, context.Response.StatusCode);
            replacedert.Equal(string.Empty, context.Request.PathBase.Value);
            replacedert.Equal("/route2/subroute2", context.Request.Path.Value);

            context = CreateRequest(string.Empty, "/route2/subroute2/subsub2");
            app.Invoke(context);
            replacedert.Equal(200, context.Response.StatusCode);
            replacedert.Equal(string.Empty, context.Request.PathBase.Value);
            replacedert.Equal("/route2/subroute2/subsub2", context.Request.Path.Value);
        }

19 Source : OwinHttpListenerResponseTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void Body_SmallerThanContentLength_ConnectionClosed()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
                    responseHeaders.Add("Content-Length", new string[] { "100" });
                    var responseStream = env.Get<Stream>("owin.ResponseBody");
                    responseStream.Write(new byte[95], 0, 95);
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                replacedert.Throws<AggregateException>(() => client.GetAsync(HttpClientAddress).Result);
            }
        }

19 Source : OwinHttpListenerResponseTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void Body_LargerThanContentLength_ConnectionClosed()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
                    responseHeaders.Add("Content-Length", new string[] { "100" });
                    var responseStream = env.Get<Stream>("owin.ResponseBody");
                    responseStream.Write(new byte[105], 0, 105);
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                replacedert.Throws<AggregateException>(() => client.GetAsync(HttpClientAddress).Result);
            }
        }

19 Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void BodyDelegate_ThrowsSync_ConnectionClosed()
        {
            bool callCancelled = false;
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    GetCallCancelled(env).Register(() => callCancelled = true);
                    var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
                    responseHeaders.Add("Content-Length", new string[] { "10" });

                    var responseStream = env.Get<Stream>("owin.ResponseBody");
                    responseStream.WriteByte(0xFF);

                    throw new NotImplementedException();
                },
                HttpServerAddress);

            try
            {
                // TODO: XUnit 2.0 adds support for replacedert.Throws<...>(async () => await myTask);
                // that way we can specify the correct exception type.
                replacedert.Throws<AggregateException>(() => SendGetRequest(listener, HttpClientAddress).Result);
            }
            finally
            {
                replacedert.True(callCancelled);
            }
        }

19 Source : OwinWebSocketTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task WebSocketUpgradeAfterHeadersSent_Throws()
        {
            ManualResetEvent sync = new ManualResetEvent(false);
            OwinHttpListener listener = CreateServer(env =>
                {
                    var accept = (WebSocketAccept)env["websocket.Accept"];
                    replacedert.NotNull(accept);

                    // Send a response
                    Stream responseStream = (Stream)env["owin.ResponseBody"];
                    responseStream.Write(new byte[100], 0, 100);
                    sync.Set();

                    replacedert.Throws<InvalidOperationException>(() =>
                    {
                        accept(
                            null,
                            async wsEnv =>
                            {
                                throw new Exception("This wasn't supposed to get called.");
                            });
                    });

                    sync.Set();

                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new ClientWebSocket())
                {
                    try
                    {
                        Task task = client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);
                        replacedert.True(sync.WaitOne(500));
                        await task;
                        replacedert.Equal(string.Empty, "A WebSocketException was expected.");
                    }
                    catch (WebSocketException)
                    {
                    }
                }
            }
        }

19 Source : ServerFactoryTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void InitializeNullProperties_Throws()
        {
            replacedert.Throws<ArgumentNullException>(() => OwinServerFactory.Initialize(null));
        }

19 Source : ServerFactoryTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void CreateNullAppFunc_Throws()
        {
            replacedert.Throws<ArgumentNullException>(() => OwinServerFactory.Create(null, new Dictionary<string, object>()));
        }

19 Source : ServerFactoryTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void CreateNullProperties_Throws()
        {
            replacedert.Throws<ArgumentNullException>(() => OwinServerFactory.Create(_notImplemented, null));
        }

19 Source : TestServerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void CancelAborts()
        {
            TestServer server = TestServer.Create(app =>
            {
                app.Run(context =>
                {
                    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
                    tcs.SetCanceled();
                    return tcs.Task;
                });
            });

            replacedert.Throws<AggregateException>(() => { string result = server.HttpClient.GetStringAsync("/path").Result; });
        }

19 Source : MapPathMiddlewareTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void NullArguments_ArgumentNullException()
        {
            var builder = new AppBuilder();
            var noMiddleware = new AppBuilder().Build<AppFunc>();
            var noOptions = new MapOptions();
            replacedert.Throws<ArgumentNullException>(() => builder.Map(null, ActionNotImplemented));
            replacedert.Throws<ArgumentNullException>(() => builder.Map("/foo", (Action<IAppBuilder>)null));
            replacedert.Throws<ArgumentNullException>(() => new MapMiddleware(null, noOptions));
            replacedert.Throws<ArgumentNullException>(() => new MapMiddleware(noMiddleware, null));
        }

19 Source : MapPredicateMiddlewareTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void NullArguments_ArgumentNullException()
        {
            var builder = new AppBuilder();
            var noMiddleware = new AppBuilder().Build<AppFunc>();
            var noOptions = new MapWhenOptions();
            replacedert.Throws<ArgumentNullException>(() => builder.MapWhen(null, UseNotImplemented));
            replacedert.Throws<ArgumentNullException>(() => builder.MapWhen(NotImplementedPredicate, (Action<IAppBuilder>)null));
            replacedert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(null, noOptions));
            replacedert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(noMiddleware, null));

            replacedert.Throws<ArgumentNullException>(() => builder.MapWhenAsync(null, UseNotImplemented));
            replacedert.Throws<ArgumentNullException>(() => builder.MapWhenAsync(NotImplementedPredicateAsync, (Action<IAppBuilder>)null));
            replacedert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(null, noOptions));
            replacedert.Throws<ArgumentNullException>(() => new MapWhenMiddleware(noMiddleware, null));
        }

19 Source : HttpApplicationExtensionsTest.cs
with MIT License
from aspnet

[Fact]
        public void AddUnity_Should_Throw_ArgumentNullException_If_HttpApplication_Is_Null()
        {
            replacedert.Throws<ArgumentNullException>(() =>
            {
                ((HttpApplication)null).AddUnity();
            });
        }

19 Source : WebHooksConfigTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void Config_Throws_IfNotSet()
        {
            // Act
            InvalidOperationException ex = replacedert.Throws<InvalidOperationException>(() => WebHooksConfig.Config);

            // replacedert
            replacedert.StartsWith("WebHooks support has not been initialized correctly. Please call the initializer 'WebHooksConfig.Initialize' on startup.", ex.Message);
        }

19 Source : EncodingUtilitiesTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [MemberData(nameof(InvalidHexData))]
        public void FromHex_Throws_OnOddInput(string invalid)
        {
            InvalidOperationException ex = replacedert.Throws<InvalidOperationException>(() => EncodingUtilities.FromHex(invalid));

            replacedert.Contains(string.Format(CultureInfo.CurrentCulture, "Input is not a valid hex-encoded string: '{0}'. Please provide a valid hex-encoded string.", invalid), ex.Message);
        }

19 Source : StorageManagerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void GetAzureStorageConnectionString_ThrowsIfNotFound()
        {
            // Arrange
            var settings = new SettingsDictionary();

            // Act
            var ex = replacedert.Throws<InvalidOperationException>(() => _manager.GetAzureStorageConnectionString(settings));

            // replacedert
            replacedert.Equal("Please provide a Microsoft Azure Storage connection string with name 'MS_AzureStoreConnectionString' in the configuration string section of the 'Web.Config' file.", ex.Message);
        }

19 Source : StorageManagerTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [MemberData(nameof(InvalidConnectionStringData))]
        public void GetCloudStorageAccount_Handles_InvalidConnectionStrings(string connectionString)
        {
            var ex = replacedert.Throws<InvalidOperationException>(() => _manager.GetCloudStorageAccount(connectionString));
            replacedert.Contains("The connection string is invalid", ex.Message);
        }

19 Source : StorageManagerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void GetCloudTable_HandlesInvalidTableName()
        {
            // Act
            var ex = replacedert.Throws<InvalidOperationException>(() => _manager.GetCloudTable("UseDevelopmentStorage=true;", "I n v a l i d / N a m e"));

            // replacedert
            replacedert.StartsWith("Could not initialize connection to Microsoft Azure Storage: Bad Request", ex.Message);
        }

19 Source : StorageManagerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void GetCloudQueue_HandlesInvalidQueueName()
        {
            // Act
            var ex = replacedert.Throws<InvalidOperationException>(() => _manager.GetCloudQueue("UseDevelopmentStorage=true;", "I n v a l i d / N a m e"));

            // replacedert
            replacedert.StartsWith("Could not initialize connection to Microsoft Azure Storage: The requested URI does not represent any resource on the server. ", ex.Message);
        }

19 Source : SqlWebHookStorePlainTextTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [MemberData(nameof(ConnectionSettingsData))]
        public void CheckSqlStorageConnectionString_Throws_IfNullOrEmptyConnectionString(ConnectionSettings connectionSettings)
        {
            // Arrange
            SettingsDictionary settings = new SettingsDictionary();
            settings.Connections.Add(WebHookStoreContext.ConnectionStringName, connectionSettings);

            // Act
            InvalidOperationException ex = replacedert.Throws<InvalidOperationException>(() => SqlWebHookStore.CheckSqlStorageConnectionString(settings));

            // replacedert
            replacedert.Equal("Please provide a SQL connection string with name 'MS_SqlStoreConnectionString' in the configuration string section of the 'Web.Config' file.", ex.Message);
        }

19 Source : NotificationDictionaryTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [MemberData(nameof(UnknownKeys))]
        public void Item_Throws_IfKeyNotFound(string key)
        {
            KeyNotFoundException ex = replacedert.Throws<KeyNotFoundException>(() => _notification[key]);

            replacedert.Equal(string.Format(CultureInfo.CurrentCulture, "No Notification setting was found with key '{0}'.", key), ex.Message);
        }

19 Source : NotificationDictionaryTests.cs
with Apache License 2.0
from aspnet

[Theory]
        [MemberData(nameof(UnknownKeys))]
        public void Item_OnInterface_Throws_IfKeyNotFound(string key)
        {
            IDictionary<string, object> dictionary = (IDictionary<string, object>)_notification;
            KeyNotFoundException ex = replacedert.Throws<KeyNotFoundException>(() => dictionary[key]);

            replacedert.Contains("The given key was not present in the dictionary.", ex.Message);
        }

19 Source : WebHookSenderTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void SignWebHookRequest_HandlesNullWebHook()
        {
            WebHookWorkItem workItem = CreateWorkItem();
            HttpRequestMessage request = new HttpRequestMessage();
            _sender = new WebHookSenderMock(_loggerMock.Object);
            JObject body = _sender.CreateWebHookRequestBody(workItem);
            workItem.WebHook = null;

            // Act
            ArgumentException ex = replacedert.Throws<ArgumentException>(() => _sender.SignWebHookRequest(workItem, request, body));

            // replacedert
            replacedert.StartsWith("Invalid 'WebHookSenderMock' instance: 'WebHook' cannot be null.", ex.Message);
        }

See More Examples