Giter VIP home page Giter VIP logo

nsupertest's Introduction

nsupertest NuGet License

Super Test style testing for .net Core projects. (With possible support for OWIN if a server provider is written).

About

A small focused library for ergonomic functional testing of .net web api projects. Inspiration taken from the excellent Super Test libaray for testing nodejs http servers.

The goal of the library is twofold:

  1. Make it simple to setup tests against either an in memory web api server in .net or a remote one. Make it easy to switch between different servers so the same tests can be used against multiple deployment stages.
  2. Provide a nice syntax for writing assertions against http response messages.

The assertions part of the library are extensions on HttpResponseMessage, so you can even only take half, if the server part doenst interest you you are still able to take advantage of the assertions part of the library.

Why "In Memory" testing?

The big win with in memory testing is the debug story; being able to debug the test code and the server code in 1 process is very valuable and helps you quickly diagnose the reason for a test failing using the debug tools.

This is especially valuable if you are working against a pre-written set of functional tests and using them as a validation that you are fulfilling the contract of behavior specified in the suite. If your test is still red after completing what you beleive to be the feature, you can simply run through the test in debug and see whats what.

Getting started

The library is available as a nuget package.

dotnet add package nsupertest

Register servers

In order to setup a server, or target, for nsupertest to test against you need to register them with the testing library. This is done using an IRegisterServers implementation. The reason for this is that in order to test against an in memory server you want nsupertest to manage that server for you, you might not like a new server with each test or have multiple servers compete over available ports.

    public class ServerRegistrar : IRegisterServers
    {
        public void Register(ServerRegistry reg)
        {
            // use reg to register servers
        }
    }

In this example 2 servers are registered for use in the test project. A .net core webapi is being registered in memory

In memory testing

In order to test against in memory .net core servers you need to register a net core server:

    reg.RegisterNetCoreServer<Startup>("TestServer");

This registers a net core server using its startup class which is then supplied to a pretty generic web host builder. Nsupertest will manage the server in memory and when you need it you simply create a TestClient and give it the name of your server:

    TestClient client = new TestClient("TestServer");

This client can be then used to perform tests and assert against the API.

Configuration

You can also provide a configuration builder so that your in memory server can be setup for testing. In this case a configuration that uses a different json configuration file is being used.

    var config = new ConfigurationBuilder().AddJsonFile("appsettings.json");
    reg.RegisterNetCoreServer<Startup>("TestServer", config);

Proxy testing

Setting up a proxy server is very simple:

    reg.RegisterProxyServer("TestServer", "https://myserver/api/v1");

The assertion API

Once you have a TestClient in your test its quite simple to use it to make http requests and perform assertions:

    var message = await client
        .GetAsync("/values")
        .ExpectStatus(200);

This test performs a GET request against the values resource in the api and performs a status assertion, expecting a http status response code of 200.

The client part has support for the following verbs:

  • GET
  • PUT
  • POST
  • DELETE
  • PATCH

You can also use MakeRequestAsync() and pass your own request object to utilize other more obscure verbs.

Post / Put

Post allows you to post a body to the server

    await client
        .PostAsync("/persons", new {
            Age = 200,
            Name = "t1000"
        })
        .ExpectStatus(400);

You can post anonymous objects if you wish, or if you are in memory you can use the actual post model from your web api project, meaning less boilerplate code in the functional test lib.

Headers + Query

Each request method allows you to set optional parameters to set header and query variables. These are both just Dictionary<string, string> objects.

    await client
        .PostAsync("/persons", 
            body: new {
                Age = 10,
                Name = "Test"
            },
            headers: new Headers { { "nameOverride", "peter" } },
            query: new Query { { "setId", "9" } }
        )
        .ExpectStatus(200);

Assertions

The library has a set of assertions that can be used to test the http response to your call:

ExpectStatus

Expect a specific http status result:

.ExpectStatus(200); // expect OK
.ExpectStatus(HttpStatusCode.BadRequest); // expect failure

ExpectBody

Expect a string body:

.ExpectBody("I expect this");

ExpectBody (Object)

Expect a C# object

var object = new { Name = "Pete" };

// request
.ExpectBody(object); // expects the declared object.

If the library cannot parse the content and create the above object the test fails. You can pass an optional parameter to this method to change the camel case behavior of the Json serializer.

ExpectResponse

Provides a callback allowing you to perform assertions on the raw http response object:

.ExpectResponse(resp => {
    // assert against resp here
});

ExpectHeader

Assert the existence of a header value pair:

.ExpectHeader("TestHeader", "TestValue");

Attribution

The JSON schema validation is provided by the awesome NJsonSchema library.

nsupertest's People

Contributors

asgeirbjo avatar gislikonrad avatar helgihaf avatar pshort avatar viktooooor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nsupertest's Issues

About .net core version

Hi man, very cool that you got the .net core version going ๐Ÿ‘
Just a thought, maybe put it in the read me that version 2 is .net core and version 1 is the standard .net version, and or point to the different branches for the different .net versions

Headers seem to not be working for bearer tokens

var message = await client.GetAsync("/myresource", headers: new Headers { {"Authorization", "Bearer " + token} }) .ExpectStatus(200);

Resulting in 401 with the server. Somehow this isnt getting onto the request correctly

Readme

Readme with some examples would not hurt anyone :) If you want I can create some docs for this and submit a pull request

Feature request

I mate, great lib, use it ALL the time! What an awesome library you have created, I mean all praises. One thing, i have a feature request. I would be able to use enums in the expect method instead of the int status codes.

Model validation

When writing validation tests to check if properties in a model are in the correct format
it would be nice if nsupertest could give back the returned content with a 400 bad request so it would be easy to assert in the test.

example of returned 400 bad request
{
"message": "The request is invalid.",
"modelState": {
"body.SomeCode": [
"The field SomeCode must match the regular expression '^[A-Z]{3}'."
]
}
}

Error Occurred once Installed for Version 0.1.22

Once the 0.1.22 version of the Nuget Package is installed it's not possible to see the Installed packages in the nuget package manager for the solution. Instead an error is displayed that says "Error occurred", and that's it.

Deleting the project and starting from scratch did not help and neither did deleting all the installed packages and re-installing them.

Downgrading to version 0.1.21 fixed the problem.

Build failing

Since i know for a fact that you are using AppVeyor now and not Travis, maybe change out the build badge. Just hurts the eye seeing these failed build when it is not even true

Feature request: Multipart message with POST

Hi Peter

Would you consider adding attachments with POST messages? (multiple files)

Example

        Server
            .Post(BaseRoute)
            .Send(ValidEmailObject)
            .Attach('file1', 'test/fixtures/avatar.jpg')
            .Attach('file2', 'test/fixtures/pokeee.jpg')
            .Set(Authorization, GenerateVendorToken())
            .ExpectUnauthorized()
            .End();

Schema Validation

Assert Schemas -> .ExpectSchema()? or some json schema library or definition....

Cannot add cookies by set method.

I am unable to add cookie by set method, it adds other headers but not cookie.
var cookie = "user=abc";
Server
.Get("/")
.Set("Accept", "application/json")
.Set("Cookie", cookie)
.Expect(200)
.End();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.