<commit_before>---
published: true
title: Mocking via interface vs delegate vs virtual method in C#
description: "Let's consider 3 options on how to mock a single method: interface, delegate, virtual method"
layout: post
tags: [csharp, NUnit, NSubstitute, mocking, dotnet]
comments: true
---

Quite often, I face a dilemma on how to mock a single method. It looks like overengineering for nothing, when the method is being moved outside of the class, just to mock it afterward. But what alternatives do we have? 

Before answering the question let's consider a specific specific code example. We have a model `Customer` and business logic implemented in `ICustomerService` and `CustomerService`.

```c#
public class Customer
{
    public Customer(Guid id, DateTime createdAt, string name)
    {
        Id = id;
        CreatedAt = createdAt;
        Name = name;
    }

    public Guid Id { get; }
    public DateTime CreatedAt { get; }
    public string Name { get; }
}

public interface ICustomerService
{
    Customer RegisterCustomer(string name);
}

public class CustomerService : ICustomerService<commit_msg>Mocking via interface vs delegate vs virtual method in C#<commit_after>---
published: true
title: Mocking via interface vs delegate vs virtual method in C#
description: "Let's consider 3 options on how to mock a single method: interface, delegate, virtual method"
layout: post
tags: [csharp, NUnit, NSubstitute, mocking, dotnet]
comments: true
---

Quite often, I face a dilemma on how to mock a single method. It looks like overengineering for nothing, when the method is being moved outside of the class, just to mock it afterward. But what alternatives do we have? 

Before answering the question let's consider a specific code example. We have a model `Customer` and business logic implemented in `ICustomerService` and `CustomerService`.

```c#
public class Customer
{
    public Customer(Guid id, DateTime createdAt, string name)
    {
        Id = id;
        CreatedAt = createdAt;
        Name = name;
    }

    public Guid Id { get; }
    public DateTime CreatedAt { get; }
    public string Name { get; }
}

public interface ICustomerService
{
    Customer RegisterCustomer(string name);
}

public class CustomerService : ICustomerService
{'fraction_non_alphanumeric': 0.06754966887417219, 'fraction_numerical': 0.0008830022075055188, 'mean_word_length': 3.8731182795698924, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '937806', 'n_tokens_mistral': 599, 'n_tokens_neox': 578, 'n_words': 293}