• Stars
    star
    758
  • Rank 57,725 (Top 2 %)
  • Language
    C#
  • License
    Other
  • Created over 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Fluent testing framework for ASP.NET Web API 2.

MyTested.WebApi  MyTested.WebApi - Fluent testing
  framework for ASP.NET Web API 2

Diamond Sponsors

Gold Sponsors

Special Sponsors

The Ultimate Cross-Platform .NET Framework JetBrains

Project Description

MyTested.WebApi is a unit testing library providing easy fluent interface to test the ASP.NET Web API 2 framework. It is testing framework agnostic, so you can combine it with a test runner of your choice (e.g. NUnit, xUnit, etc.). Inspired by ChaiJS.

Build status NuGet Version Coverage Status License

Sponsors & Backers

MyTested.WebApi is a community-driven open source library. It's an independent project with its ongoing development made possible thanks to the support by these awesome backers. If you'd like to join them, please consider:

What's the difference between Patreon and OpenCollective?

Funds donated via both platforms are used for development and marketing purposes. Funds donated via OpenCollective are managed with transparent expenses. Your name/logo will receive proper recognition and exposure by donating on either platform.

Documentation

Please see the documentation for full list of available features. Everything listed in the documentation is 100% covered by more than 800 unit tests and should work correctly. Almost all items in the issues page are expected future features and enhancements.

Installation

You can install this library using NuGet into your Test class project. It will automatically reference the needed dependencies of Microsoft.AspNet.WebApi.Core (≥ 5.1.0) and Microsoft.Owin.Testing (≥ 3.0.1) for you. .NET 4.5+ is needed. Make sure your solution has the same versions of the mentioned dependencies in all projects where you are using them. For example, if you are using Microsoft.AspNet.WebApi.Core 5.2.3 in your Web project, the same version should be used after installing MyTested.WebApi in your Tests project.

Install-Package MyTested.WebApi

After the downloading is complete, just add using MyTested.WebApi; and you are ready to test in the most elegant and developer friendly way.

using MyTested.WebApi;

For other interesting packages check out:

How to use

Make sure to check out the documentation for full list of available features. You can also check out the provided samples for real-life ASP.NET Web API application testing.

Basically you can create a test case by using the fluent API the library provides. You are given a static MyWebApi class from which all assertions can be easily configured.

namespace MyApp.Tests.Controllers
{
    using MyTested.WebApi;
	
    using MyApp.Controllers;
    using NUnit.Framework;

    [TestFixture]
    public class HomeControllerShould
    {
        [Test]
        public void ReturnOkWhenCallingGetAction()
        {
            MyWebApi
                .Controller<HomeController>()
                .Calling(c => c.Get())
                .ShouldReturn()
                .Ok();
        }
    }
}

The example uses NUnit but you can use whatever testing framework you want. Basically, MyTested.WebApi throws an unhandled exception if the assertion does not pass and the test fails.

Here are some random examples of what the fluent testing API is capable of:

// tests a route for correct controller, action and resolved route values
MyWebApi
    .Routes()
    .ShouldMap("api/WebApiController/SomeAction/5")
    .WithJsonContent(@"{""SomeInt"": 1, ""SomeString"": ""Test""}")
    .And()
    .WithHttpMethod(HttpMethod.Post)
    .To<WebApiController>(c => c.SomeAction(5, new RequestModel
    {
        SomeInt = 1,
        SomeString = "Test"
    }))
    .AndAlso()
    .ToNoHandler()
    .AndAlso()
    .ToValidModelState();

// injects dependencies into controller
// and mocks authenticated user
// and tests for valid model state
// and tests response model from Ok result with specific assertions
MyWebApi
    .Controller<WebApiController>()
    .WithResolvedDependencyFor<IInjectedService>(mockedInjectedService)
    .WithResolvedDependencyFor<IAnotherInjectedService>(anotherMockedInjectedService);
    .WithAuthenticatedUser(user => user.WithUsername("NewUserName"))
    .Calling(c => c.SomeAction(requestModel))
    .ShouldHave()
    .ValidModelState()
    .AndAlso()
    .ShouldReturn()
    .Ok()
    .WithResponseModelOfType<ResponseModel>()
    .Passing(m =>
    {
        Assert.AreEqual(1, m.Id);
        Assert.AreEqual("Some property value", m.SomeProperty);
    });

// tests whether model state error exists by using lambda expression
// and specific tests for the error messages
MyWebApi
    .Controller<WebApiController>()
    .Calling(c => c.SomeAction(requestModel))
    .ShouldHave()
    .ModelStateFor<RequestModel>()
    .ContainingModelStateErrorFor(m => m.SomeProperty).ThatEquals("Error message") 
    .AndAlso()
    .ContainingModelStateErrorFor(m => m.SecondProperty).BeginningWith("Error") 
    .AndAlso()
    .ContainingModelStateErrorFor(m => m.ThirdProperty).EndingWith("message") 
    .AndAlso()
    .ContainingModelStateErrorFor(m => m.SecondProperty).Containing("ror mes"); 
	
// tests whether the action throws internal server error
// with exception of certain type and with certain message
MyWebApi
    .Controller<WebApiController>()
    .Calling(c => c.SomeAction())
    .ShouldReturn()
    .InternalServerError()
    .WithException()
    .OfType<SomeException>()
    .AndAlso()
    .WithMessage("Some exception message");
	
// run full pipeline integration test
MyWebApi
    .Server()
    .Working(httpConfiguration)
    .WithHttpRequestMessage(
        request => request
            .WithMethod(HttpMethod.Post)
            .WithRequestUri("api/WebApiController/SomeAction/1"))
    .ShouldReturnHttpResponseMessage()
    .WithStatusCode(HttpStatusCode.OK)
    .AndAlso()
    .ContainingHeader("MyCustomHeader");

License

Code by Ivaylo Kenov. Copyright 2015 Ivaylo Kenov.

This library is intended to be used in both open-source and commercial environments. To allow its use in as many situations as possible, MyTested.WebApi is dual-licensed. You may choose to use MyTested.WebApi under either the Apache License, Version 2.0, or the Microsoft Public License (Ms-PL). These licenses are essentially identical, but you are encouraged to evaluate both to determine which best fits your intended use.

Refer to the LICENSE for detailed information.

Any questions, comments or additions?

If you have a feature request or bug report, leave an issue on the issues page or send a pull request. For general questions and comments, use the StackOverflow forum.

More Repositories

1

MyTested.AspNetCore.Mvc

Fluent testing library for ASP.NET Core MVC.
C#
1,712
star
2

Code.It.Up.TV

YouTube Channel for Advanced C# Lessons
JavaScript
514
star
3

AspNet.Mvc.TypedRouting

A collection of extension methods providing strongly typed routing and link generation for ASP.NET Core MVC projects.
C#
486
star
4

Architecture-of-ASP.NET-Core-Microservices-Applications

Architecture of ASP.NET Core Microservices Applications
C#
281
star
5

ASP.NET-Server-Architectures

C#
185
star
6

CSharp-Web-Server

C#
185
star
7

Software-Architecture-Series

Become a better software engineer 👈
162
star
8

C-Sharp-Async-Await-In-Detail

JavaScript
156
star
9

ASP.NET-Core-Project-Car-Renting-System

C#
142
star
10

ASP.NET-MVC-Lambda-Expression-Helpers

A collection of extension methods providing strongly typed link generation for ASP.NET MVC 5 projects.
C#
139
star
11

Domain-Driven-Design-with-ASP.NET-Core-Microservices

Domain-Driven Design with ASP.NET Core Microservices
C#
123
star
12

AspNetCore.Mvc.HttpActionResults

A collection of HTTP status code action results and controller extension methods for ASP.NET Core MVC projects.
C#
100
star
13

CSharp-ORM-Battle

C#
100
star
14

Identity-Server-Demystified

C#
93
star
15

Docker-From-ABC-To-XYZ

93
star
16

Let-s-Get-Functional-With-C-Sharp

C#
86
star
17

MyCoolWebServer

C#
84
star
18

Microservice-Based-Applications

80
star
19

Microservices-Eventual-Consistency-Done-Right

C#
79
star
20

Process-Automation-with-ASP.NET-Core-Microservices

C#
75
star
21

C-Sharp-API-Scenarios-REST-GraphQL-gRPC

C#
64
star
22

GameStoreSimpleMvc

C#
55
star
23

JustChess

Console Chess Game for the OOP course at Telerik Academy
C#
54
star
24

MyTested.HttpServer

Fluent testing framework for remote HTTP servers.
C#
51
star
25

Ticketing-System-ASP.NET-MVC-5

Exam preparation for the Telerik Academy ASP.NET MVC 5 course.
C#
46
star
26

Telerik-Academy-Courses

MEAN Stack Application
CSS
45
star
27

Music-Artists

JavaScript
38
star
28

TestRepoCode

Testing GitHub
C#
36
star
29

express-architecture

JavaScript
36
star
30

express-template

Per type architecture for Node.js, Express, Mongoose and Handlebars.
JavaScript
35
star
31

AzurePipelinesBlog

C#
34
star
32

LearningSystemDemo

C#
32
star
33

ModPanel

C#
31
star
34

Jetpack-Joyride-Unity-3D

C#
30
star
35

Cool-Demo-Project

This is my cool demo project for a SoftUni lecture!
C#
27
star
36

AngularJS-SocialNetwork

JavaScript
25
star
37

ExpressionTrees

C#
25
star
38

ivaylokenov

24
star
39

Telerik-Academy-Tasks

My programming experience at Telerik Academy
JavaScript
23
star
40

Flappy-Bird-Unity-3D

C#
20
star
41

TestGitRepo

This is a test repository.
20
star
42

mocking-demo

C#
19
star
43

EasyPTC

C#
19
star
44

Student-System-Live-Demo

Entity Framework Code First and Repository Pattern Live Demo
JavaScript
18
star
45

DynamicXMLBuilder

C#
18
star
46

MVC.Models

JavaScript
17
star
47

TelerikHackaton.Ruler

C#
16
star
48

Roslyn-Overview

Overview of the .NET Compiler Platform
C#
16
star
49

Street-Fitness-Kendo-Mobile

KendoMobileStreetFitness
JavaScript
13
star
50

SoftUniDemoGitHubProject

Demo project for SoftUni Fundamentals
12
star
51

TestGit

Using this repository for a GitHub lecture at SoftUni
JavaScript
10
star
52

FundamentalsGitHubDemo

This is a demo repository for a lecture at SoftUni.
JavaScript
4
star