Skip to content

Assertions

Michael W Powell edited this page Dec 8, 2020 · 1 revision

Assertions can be written using xUnit.net assertions, or the library of your choice; our recommendation is xunit.fluently.assert, and, although documentation is sparse at the time of this writing, usage is straightforward, and the extension methods are all provided from the familiar Xunit namespace.

Examples

Using xUnit.net assertion

// Simple assertion
[Scenario]
public void CreatingARequest(string url, HttpWebRequest request)
{
    "Given a valid HTTP URL".x(() => url = "http://www.example.com");

    "When I create an HTTP web request".x(() => request = (HttpWebRequest)WebRequest.Create(url));

    "Then the user agent is null".x(() => Assert.Null(request.UserAgent));
}

// Expected exception assertion
[Scenario]
public void UsingAnEmptyUrl(string url, Exception ex)
{
    "Given an empty URL string".x(() => url = String.Empty);

    "When create a web request".x(() => ex = Record.Exception(() => WebRequest.Create(url)));

    "Then a UriFormatException is thrown".x(() => Assert.IsType<UriFormatException>(ex));
}

Using xunit.fluently.assert assertions

Note, that for purposes of this example, we also use the same xunit.fluently.assert.exceptionally for fluent exception handling.

using Xunit;

// Simple assertion
[Scenario]
public void CreatingARequest(string url, HttpWebRequest request)
{
    "Given a valid HTTP URL".x(() => url = "http://www.example.com");

    "When I create an HTTP web request".x(() => request = WebRequest.Create(url).AssertIsType<HttpWebRequest>());
    //                                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    "Then the user agent is null".x(() => request.UserAgent.AssertNull());
    //                                                      ^^^^^^^^^^^^
}

// Expected exception assertion
[Scenario]
public void UsingAnEmptyUrl(string url, Exception ex, Action onCreateWebRequest)
{
    "Given an empty URL string".x(() => url = string.Empty);

    "Arrange to create bad web request".x(() => onCreateWebRequest = () => WebRequest.Create(url));

    "Exception is thrown when web request created".x(() => ex = onCreateWebRequest.AssertThrows<UriFormatException>());
    //                                                                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

You can assess the differences in approach and gauge for yourself how much more concise a true and proper fluent style is.

However, again, you are free to run with what you know.

Clone this wiki locally