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

Was this helpful?

  1. Moq

Custom matchers

When defining argument expectations, developers can use It.Is to apply custom predicates to incoming parameters.

mock.Verify(p => p.DoSomething(It.Is<string>(s => s.Length > 100)));

Over time, developers might want to collect these custom expressions into a library. Unfortunately, the matching expressions can't be extracted as they are because It.Is<T> accepts an Expression<Func<T, bool>> instead of a simple Func<T, bool> delegate.

To support this use case, Moq gives developers the possibility to create custom matchers. A custom matcher is an expression that wraps a delegate so that it can be used when defining an argument expectation.

public static class ParameterExpectations
{
    [Matcher]
    public static string StringLongerThan(int size) => Moq.Match.Create<string>(s => s.Length > size);
}

mock.Verify(p => p.DoSomething(ParameterExpectations.StringLongerThan(100)));
PreviousMock repositoryNextMultiple interfaces

Last updated 4 years ago

Was this helpful?