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
  • Expecting any type
  • Setting expectations on incoming type parameter
  1. Moq

Generic methods

Generic methods require type parameters to be specified to be invoked. When dealing with dependencies exposing generic methods, developers can use Moq to configure these methods accordingly by placing constraints on the incoming type parameters.

The snippets in this section will be based on the interface below:

public interface IService
{
    void DoSomething<T>(T argument);
}

Expecting any type

Like for configuring methods by accepting any parameters, methods can be configured to accept any type. This can be done with the constant It.IsAnyType.

mock.Setup(p => p.DoSomething(It.IsAny<It.IsAnyType>()))
    .Callback((object value) => TestContext.Progress.Writeline($"DoSomething: {value}"));

Setting expectations on incoming type parameter

Sometimes, the configuration needs to be more specific than what is allowed from the compiler. In this case, developers can use It.IsSubType<T> to constrain the incoming type to the same type or any of its subtypes. This allows different setups for different incoming types

mock.Setup(p => p.DoSomething(It.IsAny<It.IsSubtype<IList<string>>>()))
    .Callback((IList<string> items) => TestContext.Progress.Writeline($"Received list of {items.Count} strings"));

mock.Setup(p => p.DoSomething(It.IsAny<It.IsSubtype<IList<int>>>()))
    .Throws<ArgumentException>();
PreviousProtected membersNextDelegates

Last updated 4 years ago