Unit Testing in C#
  • Unit testing in C#
  • Unit testing
    • What to test
    • When to test
    • Qualities of a good unit test suite
    • Qualities of a good unit test
    • Dealing with dependencies
    • Running the tests
  • NUnit
    • Quick glance at NUnit
    • Creating a NUnit test project
    • Anatomy of a test fixture
    • Lifecycle of a test fixture
    • Assertions
    • Asynchronous executions
    • Parameterized tests
    • Assumptions
    • Describing your tests
  • Moq
    • Quick glance at Moq
    • Method arguments
    • Method calls
    • Properties
    • Results
    • Callbacks
    • Exceptions
    • Events
    • Verifications
    • Base class
    • Mock customization
    • Implicit mocks
    • Mock repository
    • Custom matchers
    • Multiple interfaces
    • Protected members
    • Generic methods
    • Delegates
  • AutoFixture
    • Quick glance at AutoFixture
    • Fixture
    • Create and Build
    • Type customization
    • Data annotations
    • Default configurations
    • Building custom types
    • Relays
    • Tricks
    • Idioms
    • Integration with NUnit
    • Integration with Moq
    • Combining AutoFixture with NUnit and Moq
    • Extending AutoFixture
  • Advanced topics
    • Testing HttpClient
Powered by GitBook
On this page
  1. Moq

Delegates

PreviousGeneric methodsNextQuick glance at AutoFixture

Last updated 4 years ago

Moq can be used to create fake delegates. Mocks faking delegates can be configured like normal methods to , or .

The snippets below are based on the following type

public delegate int ParseString(string value);

Moq can fake explicit delegates by simply passing their type to the constructor.

var mock = new Mock<ParseString>();

Alternatively, Moq supports delegates based on Func and Action.

var mock = new Mock<Func<string, int>>();

It is possible to configure the delegates as if they were normal methods.

mock.Setup(p => p(It.IsAny<string>()))
    .Returns(42);

Finally, Moq can generate for delegates too.

var parser = Mock.Of<ParseString>();

var func = Mock.Of<Func<string, int>>();
return a value
execute a callback
throw an exception
implicit mocks