DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Solid Testing Strategies for Salesforce Releases
  • Why We Still Struggle With Manual Test Execution in 2025
  • Why Testing is a Long-Term Investment for Software Engineers

Trending

  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Start Coding With Google Cloud Workstations
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Scaling InfluxDB for High-Volume Reporting With Continuous Queries (CQs)
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Using NSubstitute for Partial Mocks

Using NSubstitute for Partial Mocks

Sometimes you need to implement partial mocks in your automated testing. We take a look at how to use NSubstitute to do this with your .NET code.

By 
Paul Michaels user avatar
Paul Michaels
·
Mar. 28, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
10.9K Views

Join the DZone community and get the full member experience.

Join For Free

I have previously written about how to, effectively, subclass using NSubstitute; in this post, I'll cover how to partially mock out that class.

Before I get into the solution, what follows is a workaround to allow badly written or legacy code to be tested without refactoring. If you're reading this and thinking you need this solution then my suggestion would be to refactor and use some form of dependency injection. However, for various reasons, that's not always possible (hence this post).

Here's our class to test:

public class MyFunkyClass
{
    public virtual void MethodOne()
    {        
        throw new Exception("I do some direct DB access");
    }

    public virtual int MethodTwo()
    {
        throw new Exception("I do some direct DB access and return a number");

        return new Random().Next(5);
    }

    public virtual int MethodThree()
    {
        MethodOne();
        if (MethodTwo() <= 3)
        {
            return 1;
        }

        return 2;
    }
}

Okay, so let's write our first test:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = new MyFunkyClass();

    // Act
    int result = myFunkyClass.MethodThree();

    // Assert
    Assert.Equal(2, result);
}

So, what's wrong with that?

Well, we have some (simulated) DB access, so the code will error.

The first thing to do here is to mock out MethodOne(), as it has (pseudo) DB access:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = Substitute.ForPartsOf<MyFunkyClass>();
    myFunkyClass.When(a => a.MethodOne()).DoNotCallBase();

    // Act
    int result = myFunkyClass.MethodThree();

    // Assert
    Assert.Equal(2, result);
}

Running this test now will fail with:

Message: System.Exception : I do some direct DB access and return a number.

We're past the first hurdle. We can presumably do the same thing for MethodTwo:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = Substitute.ForPartsOf<MyFunkyClass>();
    myFunkyClass.When(a => a.MethodOne()).DoNotCallBase();
    myFunkyClass.When(a => a.MethodTwo()).DoNotCallBase();

    // Act
    int result = myFunkyClass.MethodThree();

    // Assert
    Assert.Equal(2, result);
}

Now when we run the code, the test still fails, but it no longer accesses the DB:

Message: Assert.Equal() Failure
Expected: 2
Actual: 1

The problem here is that, even though we don't want MethodTwo to execute, we do want it to return a predefined result. Once we've told it not to call the base method, you can then tell it to return whatever we choose (there are separate events - see the bottom of this post for a more detailed explanation of why); for example:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = Substitute.ForPartsOf<MyFunkyClass>();
    myFunkyClass.When(a => a.MethodOne()).DoNotCallBase();
    myFunkyClass.When(a => a.MethodTwo()).DoNotCallBase();
    myFunkyClass.MethodTwo().Returns(5);

    // Act
    int result = myFunkyClass.MethodThree();

    // Assert
    Assert.Equal(2, result);
}

And now the test passes.

To understand this better, we could do this entire process manually. Only when you've felt the pain of a manual mock, can you really see what mocking frameworks such as NSubtitute are doing for us.

Let's assume that we don't have a mocking framework at all, but that we still want to test MethodThree() above. One approach that we could take is to subclass MyFunkyClass, and then test that subclass.

Here's what that might look like:

class MyFunkyClassTest : MyFunkyClass
{
    public override void MethodOne()
    {
        //base.MethodOne();
    }

    public override int MethodTwo()
    {
        //return base.MethodTwo();
        return 5;
    }
}

As you can see, now that we've subclassed MyFunkyClass, we can override the behavior of the relevant virtual methods.

In the case of MethodOne, we've effectively issued a DoNotCallBase(), (by not calling base!).

For MethodTwo, we've issued a DoNotCallBase, and then a Returns statement.

Let's add a new test to use this new, manual method:

[Fact]
public void Test2()
{
    // Arrange 
    MyFunkyClassTest myFunkyClassTest = new MyFunkyClassTest();

    // Act
    int result = myFunkyClassTest.MethodThree();

    // Assert
    Assert.Equal(2, result);
}

That's Much Cleaner - Why Not Always Use Manual Mocks?

It is much cleaner if you always want MethodThree to return 5. Once you need it to return 2 then you have two choices, either you create a new mock class, or you start putting logic into your mock. The latter, if done wrong, can end up with code that is unreadable and difficult to maintain; and if done correctly will end up in a mini version of NSubstitute.

Finally, however, well, you write the mocks, as soon as you have more than one for a single class then every change to the class (for example, changing a method's parameters or return type) results in a change to more than one test class.

It's also worth mentioning again that this problem is one that has already been solved, cleanly, by dependency injection.

Testing

Published at DZone with permission of Paul Michaels, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Solid Testing Strategies for Salesforce Releases
  • Why We Still Struggle With Manual Test Execution in 2025
  • Why Testing is a Long-Term Investment for Software Engineers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!