TestBase 4.0.7

*TestBase* gives you a flying start with
- fluent assertions that are easy to extend
- tools for testing with dependencies on AspNetMvc, HttpClient, Ado.Net, Streams

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(), ...
- Stream.ShouldHaveSameStreamContentAs(), Stream.ShouldContain()

UnitUnderTest.Action()
   .ShouldNotBeNull()
   .ShouldEqualByValue(new {Id=1, Payload=expected} )
   .Payload
       .ShouldMatchIgnoringCase("I expected this")
   .Should(somePredicate);
```

TestBase.HttpClient.Fake
------------------------

```
 var uut = new FakeHttpClient()
       .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/this")).Returns(response)
       .Setup(x=>x.Method==HttpMethod.Put).Returns(new HttpResponseMessage(HttpStatusCode.Accepted))
```

TestBase.FakeDb
------------------
`FakeDbConnection`

```
- db.SetupForQuery(…)
- db.SetupForExecuteNonQuery(…)
- db.ShouldHaveUpdated("tableName", …)
- db.ShouldHaveSelected("tableName", …)
- db.ShouldHaveUpdated("tableName", …)
- db.ShouldHaveDeleted("tableName", …)
- db.ShouldHaveInvoked(cmd => predicate(cmd))
- db.ShouldHaveXXX().ShouldHaveParameter("name", value)
- db.Verify(x=>x.CommandText.Matches("Insert [case] .*") && x.Parameters["id"].Value==1)
```

TestBase.Mvc
------------
```
ControllerUnderTest.Action()
 .ShouldbeViewResult()
 .ShouldHaveModel<TModel>()
 .ShouldEqualByValue(expected)
ControllerUnderTest.Action()
 .ShouldBeRedirectToRouteResult()
 .ShouldHaveRouteValue("expectedKey", [Optional] "expectedValue");

ShouldHaveViewDataContaining(), ShouldBeJsonResult() etc.
```

TestBase.Mvc Version 4 for netstandard20 & AspNetCore Mvc
---------------------------------------------------------

- Test most controllers with zero setup using `controllerUnderTest.WithControllerContext(actionUnderTest)` :

```
[Test]
public void ShouldBeViewWithModel_ShouldAssertViewResultAndNameAndModel()
{
   var controllerUnderTest = new AController().WithControllerContext("Action");
   
   controllerUnderTest
       .Action().ShouldBeViewWithModel<AClass>("ViewName")
       .ShouldBeOfType<AClass>()
       .FooterLink.ShouldBe("/AController/ActionName");
}

```

- Test more complex controller/application dependencies using `HostedMvcTestFixtureBase` and specify your MVCApplications `Startup` class:

```
[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 );
}
```

TestBase.Mvc Version 3 for Net4
-------------------------------

`Controller.WithHttpContextAndRoutes()` fakes your http request &amp; context.
Use the RegisterRoutes method of your actual application to test Controller.Url with your application's configured routes.

```
ControllerUnderTest
 .WithHttpContextAndRoutes(
   RouteConfig.RegisterRoutes,
   "/incomingurl")

ApiControllerUnderTest.WithWebApiHttpContext&lt;T&gt;(
   httpMethod,
   requestUri,
   routeTemplate)
```

Testable Logging with `StringListLogger`.
Mix and match with your favourite test runners and frameworks.

- Building on Mono : define compile symbol NoMSTest to remove dependency on Microsoft.VisualStudio.QualityTools.UnitTestFramework

There is a newer version of this package available.
See the version list below for details.
Install-Package TestBase -Version 4.0.7
dotnet add package TestBase --version 4.0.7
<PackageReference Include="TestBase" Version="4.0.7" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add TestBase --version 4.0.7
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

TestBase gives you a flying start with

  • fluent assertions that are easy to extend
  • infrastructure for testing with dependencies on AspNetMvc, HttpClient, Ado.Net, Streams

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() ShouldNotBeNullOrEmptyOrWhiteSpace(), ShouldEqualIgnoringCase(), ShouldBeContainedIn(), ...
- numeric.ShouldBeBetween(), ShouldEqualWithTolerance(), GreaterThan, LessThan, GreaterOrEqualTo ...
- IEnumerable.ShouldAll(), ShouldContain(), ShouldNotContain(), ShouldBeEmpty(), ShouldNotBeEmpty() ...
- Stream.ShouldHaveSameStreamContentAs() , Stream.ShouldContain()
- ShouldBe(), ShouldNotBe(), ShouldBeOfType(), ...

UnitUnderTest.Action()
    .ShouldNotBeNull()
    .ShouldEqualByValue(new {Id=1, Payload=expected, Additional=new[]{ expected1, expected2 }} )
    .Payload
        .ShouldMatchIgnoringCase("I expected this")
		.Should(someOtherPredicate);

TestBase.HttpClient.Fake

[Test]
public async Task Should_MatchTheRightExpectationAndReturnTheSetupResponse__GivenMultipleSetups()
{
    var cannedResponseThis = new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent("I Expected This")};
    var cannedResponseThat = new HttpResponseMessage(HttpStatusCode.Accepted){Headers = { {"That-Header","Value"}}};

    var uut = new FakeHttpClient()
        .Setup(x=>x.Method==HttpMethod.Put).Returns(new HttpResponseMessage(HttpStatusCode.Accepted))
        .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/this")).Returns(thisResponse)
        .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/that")).Returns(thatResponse)
        .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/forbidden")).Returns(new HttpResponseMessage(HttpStatusCode.Forbidden));

    (await uut.GetAsync("http://localhost/that")).ShouldEqualByValue(thatResponse);

    (await uut.GetAsync("http://localhost/forbidden")).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}

TestBase.FakeDb

Works with Ado.Net and technologies on top of it, including Dapper.

- fakeDbConnection.SetupForQuery(IEnumerable<TFakeData>; )
- fakeDbConnection.SetupForQuery(IEnumerable<Tuple<TFakeDataForTable1,TFakeDataForTable2>> )
- fakeDbConnection.SetupForQuery(fakeData, new[] {"FieldName1", FieldName2"})
- fakeDbConnection.SetupForExecuteNonQuery(rowsAffected)
- fakeDbConnection.ShouldHaveUpdated("tableName", [Optional] fieldList, whereClauseField)
- fakeDbConnection.ShouldHaveSelected("tableName", [Optional] fieldList, whereClauseField)
- fakeDbConnection.ShouldHaveUpdated("tableName", [Optional] fieldList, whereClauseField)
- fakeDbConnection.ShouldHaveDeleted("tableName", whereClauseField)
- fakeDbConnection.ShouldHaveInvoked(cmd => predicate(cmd))
- fakeDbConnection.ShouldHaveXXX().ShouldHaveParameter("name", value)
- fakeDbConnection.Verify(x=>x.CommandText.Matches("Insert [case] .*") && x.Parameters["id"].Value==1)

TestBase.Mvc

ControllerUnderTest.Action()
  .ShouldbeViewResult()
  .ShouldHaveModel<TModel>()
  .ShouldEqualByValue(expected)
ControllerUnderTest.Action()
  .ShouldBeRedirectToRouteResult()
  .ShouldHaveRouteValue("expectedKey", [Optional] "expectedValue");

ShouldHaveViewDataContaining(), ShouldBeJsonResult() etc.

TestBase.Mvc Version 4 for netstandard20 & AspNetCore Mvc

  • Test most controllers with zero setup using controllerUnderTest.WithControllerContext(actionUnderTest) :
[Test]
public void ShouldBeViewWithModel_ShouldAssertViewResultAndNameAndModel()
{
    var controllerUnderTest = new AController().WithControllerContext("Action");
    
    var result= controllerUnderTest.ActionName().ShouldBeViewWithModel<AClass>("ViewName");
    
    result.ShouldBeOfType<AClass>().FooterLink.ShouldBe("/AController/ActionName");
}

  • Test controllers with complex application dependencies using HostedMvcTestFixtureBase and specify your MVCApplications Startup class:
[TestFixture]
public class WhenTestingControllersUsingAspNetCoreTestTestServer : HostedMvcTestFixtureBase
{
    [TestCase("/dummy/action?id={id}")]
    public async Task Get_Should_ReturnActionResult(string url)
    {
        var httpClient=GivenClientForRunningServer<Startup>();
        GivenRequestHeaders(httpClient, "CustomHeader", "HeaderValue1");
            
        var result= await httpClient.GetAsync(url.Formatz(new {Guid.NewGuid()}));

        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 );
    }
}

TestBase.Mvc Version 3 for Net4

Use the Controller.WithHttpContextAndRoutes() extension methods to fake the
http request &amp; 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&lt;RouteCollection&gt; mvcApplicationRoutesRegistration, 
    [optional] string requestUrl,
    [Optional] string query = "",
    [Optional] string appVirtualPath = "/",
    [Optional] HttpApplication applicationInstance)

ApiControllerUnderTest.WithWebApiHttpContext&lt;T&gt;(
    HttpMethod httpMethod, 
    [Optional] string requestUri,
    [Optional] string routeTemplate)

Can be used in both NUnit & MS UnitTestFramework test projects.

Testable Logging with StringListLogger:

MS Logging: ILoggerFactory factory=new LoggerFactory.AddProvider(new StringListLoggerProvider())
Serilogging: new LoggerConfiguration().WriteTo.StringList(stringList).CreateLogger()
//
var logger= factory.CreateLogger("Test1") ; ... ; StringListLogger.Instance.LoggedLines.ShouldContain(x=>x.Matches("kilroy was here")
  • Building on Mono : define compile symbol NoMSTest to remove dependency on Microsoft.VisualStudio.QualityTools.UnitTestFramework

ChangeLog

4.0.7.0 Added TestBase.FakeHttpClient. Added Should(predicate,...) as synonym of ShouldHave(predicate,...)
4.0.6.2 TestBase.Mvc can run controller actions on aspnetcore using controller.WithControllerContext()
4.0.5.2 TestBase.Mvc partially ported to AspNetcore
4.0.4.0 StreamShoulds
4.0.3.0 StringListLogger as MS Logger and as Serilogger
4.0.1.0 Port to NetCore
3.0.3.0 Improves FakeDb setup
3.0.x.0 adds and/or corrects missing Shoulds()
2.0.5.0 adds some intellisense and FakeDbConnection.Verify(..., message,args) overload

TestBase gives you a flying start with

  • fluent assertions that are easy to extend
  • infrastructure for testing with dependencies on AspNetMvc, HttpClient, Ado.Net, Streams

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() ShouldNotBeNullOrEmptyOrWhiteSpace(), ShouldEqualIgnoringCase(), ShouldBeContainedIn(), ...
- numeric.ShouldBeBetween(), ShouldEqualWithTolerance(), GreaterThan, LessThan, GreaterOrEqualTo ...
- IEnumerable.ShouldAll(), ShouldContain(), ShouldNotContain(), ShouldBeEmpty(), ShouldNotBeEmpty() ...
- Stream.ShouldHaveSameStreamContentAs() , Stream.ShouldContain()
- ShouldBe(), ShouldNotBe(), ShouldBeOfType(), ...

UnitUnderTest.Action()
    .ShouldNotBeNull()
    .ShouldEqualByValue(new {Id=1, Payload=expected, Additional=new[]{ expected1, expected2 }} )
    .Payload
        .ShouldMatchIgnoringCase("I expected this")
		.Should(someOtherPredicate);

TestBase.HttpClient.Fake

[Test]
public async Task Should_MatchTheRightExpectationAndReturnTheSetupResponse__GivenMultipleSetups()
{
    var cannedResponseThis = new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent("I Expected This")};
    var cannedResponseThat = new HttpResponseMessage(HttpStatusCode.Accepted){Headers = { {"That-Header","Value"}}};

    var uut = new FakeHttpClient()
        .Setup(x=>x.Method==HttpMethod.Put).Returns(new HttpResponseMessage(HttpStatusCode.Accepted))
        .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/this")).Returns(thisResponse)
        .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/that")).Returns(thatResponse)
        .Setup(x=>x.RequestUri.PathAndQuery.StartsWith("/forbidden")).Returns(new HttpResponseMessage(HttpStatusCode.Forbidden));

    (await uut.GetAsync("http://localhost/that")).ShouldEqualByValue(thatResponse);

    (await uut.GetAsync("http://localhost/forbidden")).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
}

TestBase.FakeDb

Works with Ado.Net and technologies on top of it, including Dapper.

- fakeDbConnection.SetupForQuery(IEnumerable<TFakeData>; )
- fakeDbConnection.SetupForQuery(IEnumerable<Tuple<TFakeDataForTable1,TFakeDataForTable2>> )
- fakeDbConnection.SetupForQuery(fakeData, new[] {"FieldName1", FieldName2"})
- fakeDbConnection.SetupForExecuteNonQuery(rowsAffected)
- fakeDbConnection.ShouldHaveUpdated("tableName", [Optional] fieldList, whereClauseField)
- fakeDbConnection.ShouldHaveSelected("tableName", [Optional] fieldList, whereClauseField)
- fakeDbConnection.ShouldHaveUpdated("tableName", [Optional] fieldList, whereClauseField)
- fakeDbConnection.ShouldHaveDeleted("tableName", whereClauseField)
- fakeDbConnection.ShouldHaveInvoked(cmd => predicate(cmd))
- fakeDbConnection.ShouldHaveXXX().ShouldHaveParameter("name", value)
- fakeDbConnection.Verify(x=>x.CommandText.Matches("Insert [case] .*") && x.Parameters["id"].Value==1)

TestBase.Mvc

ControllerUnderTest.Action()
  .ShouldbeViewResult()
  .ShouldHaveModel<TModel>()
  .ShouldEqualByValue(expected)
ControllerUnderTest.Action()
  .ShouldBeRedirectToRouteResult()
  .ShouldHaveRouteValue("expectedKey", [Optional] "expectedValue");

ShouldHaveViewDataContaining(), ShouldBeJsonResult() etc.

TestBase.Mvc Version 4 for netstandard20 & AspNetCore Mvc

  • Test most controllers with zero setup using controllerUnderTest.WithControllerContext(actionUnderTest) :
[Test]
public void ShouldBeViewWithModel_ShouldAssertViewResultAndNameAndModel()
{
    var controllerUnderTest = new AController().WithControllerContext("Action");
    
    var result= controllerUnderTest.ActionName().ShouldBeViewWithModel<AClass>("ViewName");
    
    result.ShouldBeOfType<AClass>().FooterLink.ShouldBe("/AController/ActionName");
}

  • Test controllers with complex application dependencies using HostedMvcTestFixtureBase and specify your MVCApplications Startup class:
[TestFixture]
public class WhenTestingControllersUsingAspNetCoreTestTestServer : HostedMvcTestFixtureBase
{
    [TestCase("/dummy/action?id={id}")]
    public async Task Get_Should_ReturnActionResult(string url)
    {
        var httpClient=GivenClientForRunningServer<Startup>();
        GivenRequestHeaders(httpClient, "CustomHeader", "HeaderValue1");
            
        var result= await httpClient.GetAsync(url.Formatz(new {Guid.NewGuid()}));

        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 );
    }
}

TestBase.Mvc Version 3 for Net4

Use the Controller.WithHttpContextAndRoutes() extension methods to fake the
http request &amp; 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&lt;RouteCollection&gt; mvcApplicationRoutesRegistration, 
    [optional] string requestUrl,
    [Optional] string query = "",
    [Optional] string appVirtualPath = "/",
    [Optional] HttpApplication applicationInstance)

ApiControllerUnderTest.WithWebApiHttpContext&lt;T&gt;(
    HttpMethod httpMethod, 
    [Optional] string requestUri,
    [Optional] string routeTemplate)

Can be used in both NUnit & MS UnitTestFramework test projects.

Testable Logging with StringListLogger:

MS Logging: ILoggerFactory factory=new LoggerFactory.AddProvider(new StringListLoggerProvider())
Serilogging: new LoggerConfiguration().WriteTo.StringList(stringList).CreateLogger()
//
var logger= factory.CreateLogger("Test1") ; ... ; StringListLogger.Instance.LoggedLines.ShouldContain(x=>x.Matches("kilroy was here")
  • Building on Mono : define compile symbol NoMSTest to remove dependency on Microsoft.VisualStudio.QualityTools.UnitTestFramework

ChangeLog

4.0.7.0 Added TestBase.FakeHttpClient. Added Should(predicate,...) as synonym of ShouldHave(predicate,...)
4.0.6.2 TestBase.Mvc can run controller actions on aspnetcore using controller.WithControllerContext()
4.0.5.2 TestBase.Mvc partially ported to AspNetcore
4.0.4.0 StreamShoulds
4.0.3.0 StringListLogger as MS Logger and as Serilogger
4.0.1.0 Port to NetCore
3.0.3.0 Improves FakeDb setup
3.0.x.0 adds and/or corrects missing Shoulds()
2.0.5.0 adds some intellisense and FakeDbConnection.Verify(..., message,args) overload

Release Notes

ChangeLog
---------
4.0.7.0 Added TestBase.FakeHttpClient. Added Should(predicate,...) as synonym of ShouldHave(predicate,...)
4.0.6.2 TestBase.Mvc can run controller actions on aspnetcore using controller.WithControllerContext()
4.0.5.2 TestBase.Mvc partially ported to netstandard20 / AspNetCore
4.0.4.1 StreamShoulds
4.0.3.0 StringListLogger as MS Logger and as Serilogger
4.0.1.0 Port to NetCore
3.0.3.0 Improves FakeDb setup
3.0.x.0 adds and/or corrects missing Shoulds()
2.0.5.0 adds some intellisense and FakeDbConnection.Verify(..., message,args) overload

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
4.1.4.3 1,601 11/20/2018
4.1.4.1 866 11/16/2018
4.1.3.2 861 10/28/2018
4.1.3.1 832 10/26/2018
4.1.2.7 869 10/24/2018
4.1.2.4 844 10/16/2018
4.1.2.3 1,273 5/22/2018
4.1.2.2 910 5/22/2018
4.1.2.1 924 5/22/2018
4.1.2 946 5/19/2018
4.1.1 967 4/8/2018
4.1.0 923 4/3/2018
4.0.9.2 1,092 3/31/2018
4.0.9.1 977 3/28/2018
4.0.9 1,092 3/23/2018
4.0.8 1,061 3/23/2018
4.0.7 910 3/22/2018
4.0.6.2 937 3/9/2018
4.0.6.1 915 3/7/2018
4.0.5.2 947 3/2/2018
4.0.5 924 3/1/2018
4.0.4.2 958 3/1/2018
4.0.4 924 2/25/2018
4.0.3 947 2/25/2018
4.0.2 902 2/24/2018
4.0.1 968 2/24/2018
3.1.0 1,262 7/24/2016
3.0.8.5 1,012 7/23/2016
3.0.8.3 1,053 4/14/2016
3.0.8.2 997 3/31/2016
3.0.8.1 989 3/30/2016
3.0.8 1,031 3/29/2016
3.0.7.6 1,026 3/14/2016
3.0.7.5 1,000 3/10/2016
3.0.7.4 1,034 2/11/2016
3.0.7.3 1,024 1/29/2016
3.0.6.2 1,042 1/27/2016
3.0.6.1 1,029 1/26/2016
3.0.5 1,045 1/15/2016
3.0.4 1,033 1/13/2016
3.0.3 1,022 12/28/2015
3.0.2 2,710 12/27/2013
3.0.1.1 1,060 12/23/2013
3.0.1 1,128 11/28/2013
2.0.5 1,092 11/28/2013
2.0.4.1 1,082 11/12/2013
2.0.4 1,102 11/12/2013
2.0.3.1 1,062 11/8/2013
2.0.3 1,114 11/7/2013
2.0.2 1,094 11/7/2013
2.0.1 1,102 11/1/2013
1.0.4 1,093 10/31/2013
1.0.3 1,117 10/23/2013
Show less