Found 10 packages
Test/mock (3rd party) code reliant on HttpClient, WebClient, HttpWebRequest and WebRequest.Create()
Library to mock HTTP responses in an integration or acceptance test written in C#.
A Machine.Fakes context configuration which fakes a standard http request
*TestBase* gives you a flying start with - fluent assertions that are simple to extend - sharp error messages - tools to help you test with “heavyweight” dependencies on - AspNetCore.Mvc, AspNet.Mvc 3-5, or WebApi Contexts - HttpClient - Ado.Net - Streams & Logging - Mix & match with your favourite test runners & assertions. # TestBase.HttpClient.Fake ``` //Arrange var httpClient = new FakeHttpClient() .SetupGetUrl("https://host.*/").Returns(request=> "Got:" + request.RequestUri) .SetupGetPath("/uri[Pp]attern/").Returns("stringcontent") .SetupPost(".*").Returns(response) .SetupPost(".*", new byte[]{1,2,3}).Returns(otherResponse) .SetupPost(".*", "a=1&b=2") .Returns( request => "You said : " + request.Content.ReadAsStringAsync().ConfigureFalseGetResult(), HttpStatusCode.Accepted) .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/this")).Returns(response) .Setup(x=>x.Method ==HttpMethod.Put) .Returns(new HttpResponseMessage(HttpStatusCode.Accepted)); // Act var putResponse = await httpClient.PutAsync("http://localhost/thing", new StringContent("{a=1,b=2}")); var postResponse= await httpClient.PostAsync("http://[::1]/", new StringContent("a=1&b=2")); //Debug httpClient.Invocations .ForEach(async i =>Console.WriteLine("{0} {1}",i.RequestUri, await i.Content.ReadAsStringAsync())); //Assert putResponse.StatusCode.ShouldBe(HttpStatusCode.Accepted); postResponse.ShouldBe(response); // ==> SetupPost(".*").Returns(response) was the first // matched setup. Setups are tried in first-to-last order. httpClient.Verify(x=>x.Method ==HttpMethod.Put, "Expected Put, but no matching invocations."); httpClient.Verify( x=>x.Method ==HttpMethod.Post && x.Content.ReadAsStringAsync().ConfigureFalseGetResult()=="a=1&b=2", "Expected Post a=1&b=2"); httpClient.VerifyAll(); // ==> "Exception : 4 unmatched expectations" ``` ### TestBase Chainable fluent assertions get you to the point concisely. ``` UnitUnderTest.Action() .ShouldNotBeNull() .ShouldEqualByValueExceptFor(new {Id=1, Descr=expected}, ignoreList ) .Payload .ShouldMatchIgnoringCase("I expected this") .Should(someOtherPredicate); .ShouldEqualByValue().ShouldEqualByValueExceptFor(...).ShouldEqualByValueOnMembers() work with all kinds of object and collections, and report what differed. string.ShouldMatch(pattern).ShouldNotMatch().ShouldBeEmpty().ShouldNotBeEmpty() .ShouldNotBeNullOrEmptyOrWhiteSpace().ShouldEqualIgnoringCase() .ShouldContain().ShouldStartWith().ShouldEndWith().ShouldBeContainedIn().ShouldBeOneOf().ShouldNotBeOneOf() numeric.ShouldBeBetween().ShouldEqualWithTolerance()....GreaterThan....LessThan...GreaterOrEqualTo ... ienumerable.ShouldAll().ShouldContain().ShouldNotContain().ShouldBeEmpty().ShouldNotBeEmpty() ... stream.ShouldHaveSameStreamContentAs().ShouldContain() value.ShouldBe().ShouldNotBe().ShouldBeOfType().ShouldBeAssignableTo()... .ShouldAll(predicate), .SingleOrAssertFail()... ``` See also - [TestBase](https://www.nuget.org/packages/TestBase) - [TestBase.AspNetCore.Mvc](https://www.nuget.org/packages/TestBase.AspNetCore.Mvc) - [TestBase-Mvc](https://www.nuget.org/packages/TestBase-Mvc) - [TestBase.AdoNet](https://www.nuget.org/packages/TestBase.AdoNet) - [Serilog.Sinks.ListOfString](https://www.nuget.org/packages/Serilog.Sinks.Listofstring) - [Extensions.Logging.ListOfString](https://www.nuget.org/packages/Extensions.Logging.ListOfString)
*TestBase* gets you off to a flying start when unit testing projects with dependencies. TestBase-Mvc adds a rich extensible set of fluent assertions for verifying Mvc ActionResults and for easy setup of ControllerContext and HttpContext for both Mvc and WebApi TestBase.Shoulds ------------------- Chainable fluent assertions get you to the point concisely ControllerUnderTest.Action() .ShouldbeViewResult() .ShouldHaveModel<TModel>() .ShouldEqualByValue(expected) ControllerUnderTest.Action() .ShouldBeRedirectToRouteResult() .ShouldHaveRouteValue("expectedKey", [Optional] "expectedValue"); ShouldHaveViewDataContaining(), ShouldBeJsonResult() etc. TestBase ---------- Controller extensions to fake the http request & context. By injecting the RegisterRoutes method of your MvcApplication, you can use and test Controller.Url with your application's configured routes. ControllerUnderTest .WithHttpContextAndRoutes( [Optional] Action<RouteCollection> mvcApplicationRoutesRegistration, [optional] string requestUrl, [Optional] string query = "", [Optional] string appVirtualPath = "/", [Optional] HttpApplication applicationInstance) ApiControllerUnderTest.WithWebApiHttpContext<T>( HttpMethod httpMethod, [Optional] string requestUri, [Optional] string routeTemplate)
A Machine.Fakes context configuration which fakes an ajax http request
Provides the ability to send HttpWebRequest and get HttpWebResponses without a server. You can mock all available properties from HttpWebResponse .Net object with a json configuration file. This tool is not intrusive. With dependency injection you can simply switch between your own implementation of IHttpRequester and the implementation contained in this package
*TestBase* gives you a flying start with - fluent assertions that are easy to extend - sharp error messages - tools to help you test with “heavyweight” dependencies on - AspNetCore.Mvc, AspNet.Mvc or WebApi Contexts - HttpClient - Ado.Net - Streams & Logging TestBase.Mvc is renamed to https://www.nuget.org/packages/TestBase.Mvc.AspNetCore Use https://www.nuget.org/packages/TestBase-Mvc for Mvc 4. Chainable fluent assertions get you to the point concisely: ``` - ShouldEqualByValue() & ShouldEqualByValueExceptFor() work with all kinds of object and collections, and report what differed. - string.ShouldMatch().ShouldEqualIgnoringCase(), ... - numeric.ShouldBeBetween().ShouldEqualWithTolerance(), ... - IEnumerable.ShouldAll().ShouldContain().ShouldNotContain(), ... ``` TestBase.Mvc.AspNetCore & TestBase-Mvc ------------ ``` ControllerUnderTest.Action() .ShouldbeViewResult() .ShouldHaveModel<TModel>() .Payload .ShouldEqualByValueExceptFor(new {Id=1, Payload1=expected}, ignoreFields); ControllerUnderTest.Action() .ShouldBeRedirectToRouteResult() .ShouldHaveRouteValue(""expectedKey"", [Optional] ""expectedValue""); ShouldHaveViewDataContaining(), ShouldBeJsonResult() etc. ``` Quickly test AspNetCore controllers with zero setup using `WithControllerContext()` : ``` [Test] public void ControllerUrlAndOtherPropertiesShouldWorkAsExpected__GivenControllerContext() { var uut = new FakeController().WithControllerContext(); uut.Url.Action(""a"", ""b"").ShouldEqual(""/b/a""); uut.ControllerContext.ShouldNotBeNull(); uut.HttpContext.ShouldBe(uut.ControllerContext.HttpContext); uut.ControllerContext.HttpContext.Request.ShouldNotBeNull(); uut.Request.ShouldNotBeNull(); uut.Response.ShouldNotBeNull(); uut.Url.ShouldNotBeNull(); uut.ViewData.ShouldNotBeNull(); uut.TempData.ShouldNotBeNull(); uut.MyAction(param) .ShouldBeViewResult() .ShouldHaveModel<YouSaidViewModel>() .YouSaid.ShouldBe(param); } [Test] public void ShouldBeViewWithModel_And_UrlHelper_ShouldWork() { var controllerUnderTest = new AController() .WithControllerContext(virtualPathTemplate:""/{Action}/Before/{Controller}""); var result= controllerUnderTest .Action(""SomeController"",""SomeAction"") .ShouldBeViewWithModel<AClass>(""ViewName""); .FooterLink .ShouldBe(""/SomeAction/Before/SomeController""); } ``` ... Or test against complex application dependencies using `HostedMvcTestFixtureBase` and specify your `Startup` class: ``` [TestFixture] public class Tests : HostedMvcTestFixtureBase { [TestCase(""/dummy/action?id={id}"")] public async Task Get_Should_ReturnActionResult(string url) { var id=Guid.NewGuid(); var httpClient=GivenClientForRunningServer<Startup>(); GivenRequestHeaders(httpClient, ""CustomHeader"", ""HeaderValue1""); var result= await httpClient.GetAsync(url.Formatz(new {id})); result .ShouldBe_200Ok() .Content.ReadAsStringAsync().Result .ShouldBe(""Content""); } [TestCase(""/dummy"")] public async Task Put_Should_ReturnA(string url) { var something= new Fixture().Create<Something>(); var jsonBody= new StringContent(something.ToJSon(), Encoding.UTF8, ""application/json""); var httpClient=GivenClientForRunningServer<Startup>(); GivenRequestHeaders(httpClient, ""CustomHeader"", ""HeaderValue1""); var result = await httpClient.PutAsync(url, jsonBody); result.ShouldBe_202Accepted(); DummyController.Putted.ShouldEqualByValue( something ); } } ``` See also - TestBase - TestBase-Mvc for Mvc4 - TestBase.HttpClient.Fake - TestBase.AdoNet - Serilog.Sinks.ListOfString - Extensions.Logging.ListOfString
*TestBase* gives you a flying start with - fluent assertions that are easy to extend - sharp error messages - tools to help you test with “heavyweight” dependencies on - AspNetCore.Mvc, AspNet.Mvc or WebApi Contexts - HttpClient - Ado.Net - Streams & Logging Chainable fluent assertions get you to the point concisely: ``` ControllerUnderTest.Action() .ShouldbeViewResult() .ShouldHaveModel<TModel>() .ShouldEqualByValue(expected, exceptForTheseFields); .Reference .ShouldMatchIgnoringCase("I expected this"); ControllerUnderTest.Action() .ShouldBeRedirectToRouteResult() .ShouldHaveRouteValue(""expectedKey"", [Optional] ""expectedValue""); ShouldHaveViewDataContaining(), ShouldBeJsonResult() etc. ``` Quickly test AspNetCore controllers with zero setup using `controllerUnderTest.WithControllerContext()` : ``` [TestFixture] public class WhenTestingControllersUsingFakeControllerContext { [Test] public void ControllerUrlAndOtherPropertiesShouldWorkAsExpected__GivenControllerContext() { var uut = new FakeController().WithControllerContext(); uut.Url.Action(""a"", ""b"").ShouldEqual(""/b/a""); uut.ControllerContext.ShouldNotBeNull(); uut.HttpContext.ShouldBe(uut.ControllerContext.HttpContext); uut.Request.ShouldNotBeNull(); uut.ViewData.ShouldNotBeNull(); uut.TempData.ShouldNotBeNull(); uut.MyAction(param) .ShouldBeViewResult() .ShouldHaveModel<YouSaidViewModel>() .YouSaid.ShouldBe(param); } [Test] public void ShouldBeAbleToUseServicesConfiguredInStartupInTests() { var moreServicesFromDI=TestServerBuilder.RunningServerUsingStartup<TStartup>().Host.ServiceProvider; var controllerUnderTest = new AController() .WithControllerContext(virtualPathTemplate:""/{Action}/Before/{Controller}""); var result= controllerUnderTest .Action(""SomeController"",""SomeAction"") .ShouldBeViewWithModel<AClass>(""ViewName""); .FooterLink .ShouldBe(""/SomeAction/Before/SomeController""); } } ``` ... Or test against complex application dependencies using `HostedMvcTestFixtureBase` and specify your `Startup` class: ``` [TestFixture] public class WhenTestingControllersUsingAspNetCoreTestTestServer : HostedMvcTestFixtureBase { [TestCase(""/dummy/action?id={id}"")] public async Task Get_Should_ReturnActionResult(string url) { var id=Guid.NewGuid(); var httpClient=GivenClientForRunningServer<Startup>(); GivenRequestHeaders(httpClient, ""CustomHeader"", ""HeaderValue1""); var result= await httpClient.GetAsync(url.Formatz(new {id})); result .ShouldBe_200Ok() .Content.ReadAsStringAsync().Result .ShouldBe(""Content""); } [TestCase(""/dummy"")] public async Task Put_Should_ReturnA(string url) { var something= new Fixture().Create<Something>(); var jsonBody= new StringContent(something.ToJSon(), Encoding.UTF8, ""application/json""); var httpClient=GivenClientForRunningServer<Startup>(); GivenRequestHeaders(httpClient, ""CustomHeader"", ""HeaderValue1""); var result = await httpClient.PutAsync(url, jsonBody); result.ShouldBe_202Accepted(); DummyController.Putted.ShouldEqualByValue( something ); } } ``` See also - TestBase - TestBase.Mvc for Mvc4 and Mvc 5 - TestBase.HttpClient.Fake - TestBase.AdoNet - Serilog.Sinks.ListOfString - Extensions.Logging.ListOfString