Skip to content

Moq

Moq

Moq is a popular mocking library for .NET used for creating test objects and stubbing function calls. We will use it within the ModelApp to mock calls to our NewsAPI service.

Key Features

  • Strong-typed: no strings for expectations, no object-typed return values or constraints
  • Unsurpassed VS IntelliSense integration: everything supports full VS IntelliSense, from setting expectations, to specifying method call arguments, return values, etc.
  • No Record/Replay idioms to learn. Just construct your mock, set it up, use it and optionally verify calls to it (you may not verify mocks when they act as stubs only, or when you are doing more classic state-based testing by checking returned values from the object under test)
  • VERY low learning curve as a consequence of the previous three points. For the most part, you don't even need to ever read the documentation.
  • Granular control over mock behavior with a simple MockBehavior enumeration (no need to learn what's the theoretical difference between a mock, a stub, a fake, a dynamic mock, etc.)
  • Mock both interfaces and classes
  • Override expectations: can set default expectations in a fixture setup, and override as needed on tests
  • Pass constructor arguments for mocked classes
  • Intercept and raise events on mocks
  • Intuitive support for out/ref arguments

Example

var mock = new Mock<ILoveThisLibrary>();

// WOW! No record/replay weirdness?! :)
mock.Setup(library => library.DownloadExists("2.0.0.0"))
    .Returns(true);

// Use the Object property on the mock to get a reference to the object
// implementing ILoveThisLibrary, and then exercise it by calling
// methods on it
ILoveThisLibrary lovable = mock.Object;
bool download = lovable.DownloadExists("2.0.0.0");

// Verify that the given method was indeed called with the expected value at most once
mock.Verify(library => library.DownloadExists("2.0.0.0"), Times.AtMostOnce());