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

Multiple interfaces

Classes can implement multiple interfaces. It might happen that the component under test expects the incoming dependency to implement more than one interface, like in the snippet below.

public class Dependency : IDependency, IDisposable { ... }

public class Service
{
    private readonly IDependency _dependency;

    public Service (IDependency dependency) { _dependency = dependency; }

    public void DoSomething()
    {
        using (_dependency as IDisposable) { ... }
    }

    public void Dispose() { ... }
}

While being a signal that responsibilities are not properly split across interfaces, it's something that developers need to be able to cope with while developing unit tests.

Moq offers a way to decorate a mock with additional interfaces using the construct As, giving developers the possibility to configure and verify methods of the added interface.

var mock = new Mock<IDependency>();
mock.As<IDisposable>().Setup(p => p.Dispose());

Alternatively, you can also store the reference returned by As into its own variable for later usage.

var mockDisposable = mock.As<IDisposable>();
mockDisposable.Verify(p => p.Dispose(), Times.Once());
PreviousCustom matchersNextProtected members

Last updated 4 years ago

Was this helpful?