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

Implicit mocks

Sometimes, Moq's default behaviors are just enough to proceed with the unit test. In this case, Moq offers utility methods to quickly generate a mocked object using the static factory Mock.Of<T>.

Implicit mocks are the most useful when dealing with interfaces that don't need any customization nor verification. Unlike explicitly creating a mock using the Mock<T> class constructor, Mock.Of<T> returns directly the mocked type.

var logger = Mock.Of<ILogger>();

The line above is fully equivalent to:

var mock = new Mock<ILogger>();
var logger = mock.Object;

Accessing the underlying mock

Sometimes, it can be useful to access the mock a mocked object. This can be achieved with the Mock.Get utility.

var mock = Mock.Get(logger);

Mock.Get can also be used when accessing the underlying mock of a hierarchy of properties.

var mock = new Mock<HttpContextBase>();
var context = mock.Object;
var mockRequest = Mock.Get(context.Request);
PreviousMock customizationNextMock repository

Last updated 4 years ago