• Stars
    star
    5,709
  • Rank 7,139 (Top 0.2 %)
  • Language
    C#
  • License
    Other
  • Created over 12 years ago
  • Updated 7 months ago

Reviews

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

Repository Details

The most popular and friendly mocking framework for .NET

moq

Version Downloads Documentation Discord Chat

The most popular and friendly mocking library for .NET

  var mock = new Mock<ILoveThisLibrary>();

  // WOW! No record/replay weirdness?! :)
  mock.Setup(library => library.DownloadExists("2.0.0.0"))
      .Returns(true);

  // Use the Object property on the mock to get a reference to the object
  // implementing ILoveThisLibrary, and then exercise it by calling
  // methods on it
  ILoveThisLibrary lovable = mock.Object;
  bool download = lovable.DownloadExists("2.0.0.0");

  // Verify that the given method was indeed called with the expected value at most once
  mock.Verify(library => library.DownloadExists("2.0.0.0"), Times.AtMostOnce());

Moq also is the first and only library so far to provide Linq to Mocks, so that the same behavior above can be achieved much more succinctly:

  ILoveThisLibrary lovable = Mock.Of<ILoveThisLibrary>(l =>
    l.DownloadExists("2.0.0.0") == true);

  // Exercise the instance returned by Mock.Of by calling methods on it...
  bool download = lovable.DownloadExists("2.0.0.0");

  // Simply assert the returned state:
  Assert.True(download);
  
  // If you want to go beyond state testing and want to 
  // verify the mock interaction instead...
  Mock.Get(lovable).Verify(library => library.DownloadExists("2.0.0.0"));

You can think of Linq to Mocks as "from the universe of mocks, give me one whose behavior matches this expression".

Check out the Quickstart for more examples!

What?

Moq (pronounced "Mock-you" or just "Mock") is the only mocking library for .NET developed from scratch to take full advantage of .NET Linq expression trees and lambda expressions, which makes it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn't require any prior knowledge or experience with mocking concepts.

Why?

The library was created mainly for developers who aren't currently using any mocking library (or are displeased with the complexities of some other implementation), and who are typically manually writing their own mocks (with more or less "fanciness"). Most developers in this situation also happen to be quite pragmatic and adhere to state (or classic) TDD. It's the result of feeling that the barrier of entry from other mocking libraries is a bit high, and a simpler, more lightweight and elegant approach is possible. Moq achieves all this by taking full advantage of the elegant and compact C# and VB language features collectively known as LINQ (they are not just for queries, as the acronym implies).

Moq is designed to be a very practical, unobtrusive and straight-forward way to quickly setup dependencies for your tests. Its API design helps even novice users to fall in the "pit of success" and avoid most common misuses/abuses of mocking.

When it was conceived, it was the only mocking library that went against the generalized and somewhat unintuitive (especially for novices) Record/Replay approach from all other libraries (and that might have been a good thing ;)).

Not using Record/Replay also means that it's straightforward to move common expectations to a fixture setup method and even override those expectations when needed in a specific unit test.

You can read more about the "why" and see some nice screenshots at kzu's blog.

Where?

See our Quickstart examples to get a feeling of the extremely simple API and install from NuGet.

Read about the announcement at kzu's blog. Get some background on the state of mock libraries from Scott Hanselman.

In-depth documentation is being added to the documentation website.

Who?

Moq was originally developed by Clarius, Manas and InSTEDD.

Moq uses Castle DynamicProxy internally as the interception mechanism to enable mocking.

Features at a glance

Moq offers the following features:

  • Strong-typed: no strings for expectations, no object-typed return values or constraints
  • Unsurpassed VS IntelliSense integration: everything supports full VS IntelliSense, from setting expectations, to specifying method call arguments, return values, etc.
  • No Record/Replay idioms to learn. Just construct your mock, set it up, use it and optionally verify calls to it (you may not verify mocks when they act as stubs only, or when you are doing more classic state-based testing by checking returned values from the object under test)
  • VERY low learning curve as a consequence of the previous three points. For the most part, you don't even need to ever read the documentation.
  • Granular control over mock behavior with a simple MockBehavior enumeration (no need to learn what's the theoretical difference between a mock, a stub, a fake, a dynamic mock, etc.)
  • Mock both interfaces and classes
  • Override expectations: can set default expectations in a fixture setup, and override as needed on tests
  • Pass constructor arguments for mocked classes
  • Intercept and raise events on mocks
  • Intuitive support for out/ref arguments

We appreciate deeply any feedback that you may have! Feel free to participate in the chat, or report an issue in the issue tracker.

Sponsors

Clarius Org Kirill Osenkov MFB Technologies, Inc. Stephen Shaw Torutek DRIVE.NET, Inc. Daniel Gnägi Ashley Medway Keith Pickford Thomas Bolon Kori Francis Toni Wenzel Giorgi Dalakishvili Mike James Dan Siegel Reuben Swartz Jacob Foshee Eric Johnson Norman Mackay Certify The Web Rich Lee Ix Technologies B.V. David JENNI Jonathan Oleg Kyrylchuk Mariusz Kogut Charley Wu Jakob Tikjøb Andersen Seann Alexander Tino Hager Mark Seemann Angelo Belchior Blauhaus Technology (Pty) Ltd Ken Bonny Simon Cropp agileworks-eu Zheyu Shen

Sponsor this project  

Learn more about GitHub Sponsors

More Repositories

1

GitInfo

Git and SemVer Info from MSBuild, C# and VB
Pascal
513
star
2

ThisAssembly

Exposes project and assembly level information as constants in the ThisAssembly class using source generators powered by Roslyn.
C#
418
star
3

SmallSharp

Create, edit and run multiple C# top-level programs in the same project by just selecting the startup program from the start button.
C#
279
star
4

nugetizer

A simple to understand packing model for authoring NuGet packages
C#
253
star
5

avatar

A modern compile-time generated interception/proxy library
C#
139
star
6

NuDoq

A standalone API to read .NET XML documentation files and optionally augment it with reflection information.
C#
105
star
7

dotnet-file

Download, update and sync loose files from URLs
C#
52
star
8

dotnet-vs

A global tool for managing Visual Studio installations
C#
49
star
9

DependencyInjection.Attributed

Provides compile-time discovery and code generation of service registrations from attributed types
C#
36
star
10

CloudActors

An opinionated, simplified and uniform Cloud Native actors' library that integrates with Microsoft Orleans.
C#
33
star
11

RxFree

An ultra-lightweight Rx source-only nuget to avoid depending on the full System.Reactive for IObservable<T> producers
C#
32
star
12

SponsorLink

SponsorLink: an attempt at OSS sustainability
C#
31
star
13

xunit.assemblyfixture

Provides per-assembly fixture state support for xunit
C#
24
star
14

WebSocketPipe

System.IO.Pipelines API adapter for System.Net.WebSockets
C#
24
star
15

Merq

Internal application architecture via command and event messages
C#
23
star
16

TableStorage

Repository pattern with POCO object support for storing to Azure / Cosmos DB Table Storage
C#
21
star
17

Injector

Allows injecting .NET code into another Windows process
C++
12
star
18

WebSocketeer

High-performance intuitive API for Azure Web PubSub protobuf subprotocol
C#
11
star
19

xunit.vsix

Xunit for creating VSIX integration tests
C#
10
star
20

dotnet-tor

A .NET cross-platform CLI app that uses TorSharp to run a local proxy
C#
10
star
21

oss

Basic repo configuration for my OSS projects
SCSS
10
star
22

azdo

Home for azdo.io and accompanying linkinator source
C#
9
star
23

Dynamically

Instantiate record types from dynamic data with compatible structural shapes, in-memory with no reflection or serialization, via compile-time source generators.
C#
9
star
24

Web

XLinq to Web
HTML
8
star
25

chromium

Run a portable Chromium using dotnet 6+ and nuget.
C#
8
star
26

WebSocketChannel

High-performance System.Threading.Channels API adapter for System.Net.WebSockets
C#
8
star
27

dotnet-evergreen

A dotnet tool runner that automatically updates the tool package before and while running it
C#
6
star
28

CredentialManager

Packages the Git Credential Manager cross-platform implementation for Windows, macOS and Linux for use as a generic credential manager.
C#
6
star
29

dotnet-gcm

A dotnet global tool to interface with the Git Credentials Manager Core
C#
5
star
30

dotnet-eventgrid

Azure Function app and accompanying dotnet global tool to monitor Azure EventGrid streams in real-time.
C#
5
star
31

System.Diagnostics.Tracer

An improved API on top of System.Diagnostics
C#
5
star
32

json

JsonPeek and JsonPoke tasks implementations
C#
5
star
33

dotnet-stop

Gracefully stops processes by sending them SIGINT (Ctrl+C) in a cross platform way.
C#
4
star
34

nosayudamos.org

C#
3
star
35

catbag

A repository of loose helpers, base clases and assorted code
C#
3
star
36

scraper

A web scraping app that runs on Azure Container Apps
C#
3
star
37

actions-bot

A GitHub Action that sets bot secrets as git defaults if present
3
star
38

tsh

C#
2
star
39

cloudy

Spike on cloud-first architecture for apps, heavily event-driven
C#
2
star
40

PackageReferenceCleaner

Clean your PackageReferences with PrivateAssets=all into beautiful one-liners, automatically
C#
2
star
41

shields

Custom endpoints for custom badges using https://shields.io/endpoint
C#
2
star
42

Cognitive

Unified Cognitive API for Azure, Amazon and Google
C#
2
star
43

html

Loads Html documents as XLinq XDocuments
HTML
2
star
44

epub

A lightweight library that implements EPUB standard
C#
2
star
45

sponsors

Automatically updated list of devlooped sponsors
1
star
46

yaml

YamlPeek MSBuild Task
C#
1
star
47

actions-includes

Processes include HTML comments in files and inserts the included files
PowerShell
1
star
48

jq

A nuget distribution of the official JQ implementation, for easy consumption from .NET
C#
1
star
49

Azure.Functions.OpenApi

A zero-code OpenAPI (Swagger) basic generator for Azure Functions
C#
1
star
50

Mvp.Xml

C#
1
star
51

StreamR

An opinionated streaming-based library for running assistants with support for tool/function invocation and assistant behavior composition.
C#
1
star