0
0
CsharpHow-ToBeginner · 3 min read

How to Mock in C# Test: Simple Guide with Examples

To mock in a C# test, use a mocking library like Moq to create fake objects that simulate real dependencies. You create a Mock<T> object, set up expected behavior, and use .Object to pass the mock to your test. This helps isolate the code under test from external dependencies.
📐

Syntax

Here is the basic syntax to create and use a mock with the Moq library:

  • var mock = new Mock<T>(); creates a mock object for type T.
  • mock.Setup(x => x.Method()).Returns(value); defines what the mock should return when a method is called.
  • var obj = mock.Object; gets the mocked instance to pass into your code.
csharp
var mock = new Mock<IMyService>();
mock.Setup(service => service.GetData()).Returns("mocked data");
IMyService myService = mock.Object;
💻

Example

This example shows how to mock a service interface in a unit test to isolate the tested class from external dependencies.

csharp
using System;
using Moq;

public interface IDataService
{
    string GetData();
}

public class DataProcessor
{
    private readonly IDataService _dataService;
    public DataProcessor(IDataService dataService)
    {
        _dataService = dataService;
    }

    public string Process()
    {
        var data = _dataService.GetData();
        return data.ToUpper();
    }
}

public class Program
{
    public static void Main()
    {
        var mock = new Mock<IDataService>();
        mock.Setup(ds => ds.GetData()).Returns("hello world");

        var processor = new DataProcessor(mock.Object);
        Console.WriteLine(processor.Process());
    }
}
Output
HELLO WORLD
⚠️

Common Pitfalls

Common mistakes when mocking in C# tests include:

  • Not setting up the mock method, so it returns default values (null, 0).
  • Using the real object instead of the mock, which breaks test isolation.
  • Forgetting to use .Object property to get the mocked instance.
  • Mocking concrete classes without virtual methods or interfaces, which Moq cannot mock.
csharp
/* Wrong: Using real object instead of mock */
var realService = new RealDataService();
var processor = new DataProcessor(realService); // Not isolated

/* Right: Using mock object */
var mock = new Mock<IDataService>();
mock.Setup(ds => ds.GetData()).Returns("mocked");
var processorMock = new DataProcessor(mock.Object);
📊

Quick Reference

Remember these key points when mocking in C# tests:

  • Use Mock<T> to create mocks for interfaces or virtual methods.
  • Use Setup to define method behavior.
  • Access the mocked instance with .Object.
  • Verify calls with Verify if needed.

Key Takeaways

Use Moq library to create mocks for interfaces or virtual methods in C# tests.
Always set up expected method calls with .Setup() to control mock behavior.
Pass the mock instance using .Object to the class under test.
Avoid using real objects in tests to keep them isolated and reliable.
Verify mock interactions with .Verify() to ensure expected calls happen.