Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8837039
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T09:37:39+00:00 2026-06-14T09:37:39+00:00

I am currently trying to learn DI & Mocking, with Unity and NSubstitute. I

  • 0

I am currently trying to learn DI & Mocking, with Unity and NSubstitute. I am also using an automocking extension taken from this question: Is this possible with Unity (Instead of Castle Windsor)?

In my unit test below I am trying to set an NSubstitute return value of 10 from my method Add(). However when debugging through the controller call the assigned value is the default 0 rather than the expected 10. The proxy does not seem to be intercepting the method call.

I suspect this is caused by not registering my Types/container correctly, anybody able to point me in the right direction?

[TestFixture]
public class ApplicationControllerTests
{
    private IUnityContainer _container;
    private ApplicationController _controller;
    private ISampleService _sampleService;

    [SetUp]
    public void SetUp()
    {
        _container = new UnityContainer().AddExtension(new AutoMockingContainerExtension());
        _controller = _container.Resolve<ApplicationController>();
        _sampleService = _container.Resolve<ISampleService>();
    }

    [Test]
    public void TestSampleService()
    {
        // This line is not working
        _sampleService.Add(Arg.Any<int>(), Arg.Any<int>()).Returns(10);

        var result = _controller.Index();

        _sampleService.Received().Add(Arg.Any<int>(), Arg.Any<int>());
    }
}

public class AutoMockingContainerExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        var strategy = new AutoMockingBuilderStrategy(Container);

        Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
    }

    class AutoMockingBuilderStrategy : BuilderStrategy
    {
        private readonly IUnityContainer _container;

        public AutoMockingBuilderStrategy(IUnityContainer container)
        {
            _container = container;
        }

        public override void PreBuildUp(IBuilderContext context)
        {
            var key = context.OriginalBuildKey;

            if (key.Type.IsInterface && !_container.IsRegistered(key.Type))
                context.Existing = CreateSubstitute(key.Type);
        }

        private static object CreateSubstitute(Type type)
        {
            return Substitute.For(new[] { type }, null);
        }
    }
}

And my controller code

public class ApplicationController : BaseController
{
    private readonly ISampleService _sampleService;

    public ApplicationController(ISampleService sampleService)
    {
        _sampleService = sampleService;
    }

    public ActionResult Index()
    {
        var result = _sampleService.Add(2, 3);

        // result is 0, expected 10 ??

        return View();
    }
}

public interface ISampleService
{
    int Add(int first, int second);
}

public class SampleService : ISampleService
{
    public int Add(int first, int second)
    {
        return first + second;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T09:37:41+00:00Added an answer on June 14, 2026 at 9:37 am

    Actually Tormod is right the problem is that the AutoMockingBuilderStrategy returns a different mock instance every time when somebody requests an ISampleService form the container.

    So there is a bug in my original implementation namely the AutoMockingBuilderStrategy doesn’t store the created mocks:

    Here is a fixed version:

    public class AutoMockingContainerExtension : UnityContainerExtension
    {
        protected override void Initialize()
        {
            var strategy = new AutoMockingBuilderStrategy(Container);
    
            Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
        }
    
        class AutoMockingBuilderStrategy : BuilderStrategy
        {
            private readonly IUnityContainer container;
            private readonly Dictionary<Type, object> substitutes 
               = new Dictionary<Type, object>();
    
            public AutoMockingBuilderStrategy(IUnityContainer container)
            {
                this.container = container;
            }
    
            public override void PreBuildUp(IBuilderContext context)
            {
                var key = context.OriginalBuildKey;
    
                if (key.Type.IsInterface && !container.IsRegistered(key.Type))
                {
                    context.Existing = GetOrCreateSubstitute(key.Type);
                    context.BuildComplete = true;
                }
            }
    
            private object GetOrCreateSubstitute(Type type)
            {
                if (substitutes.ContainsKey(type))
                    return substitutes[type];
    
                var substitute = Substitute.For(new[] {type}, null);
    
                substitutes.Add(type, substitute);
    
                return substitute;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm currently trying to learn WinSock coding from http://johnnie.jerrata.com/winsocktutorial/ however when I compile my
Info: I'm currently trying to learn template metaprogramming (by following this book ). One
I am currently trying to learn how to query RDF data with SPARQL using
I found this script on about.com which I'm trying to learn from on how
I found this script on about.com which I'm trying to learn from on how
I just started learning C++(coming from Java & Python) and am trying to learn
I am currently trying to learn a bit of Cocoa (using the book Cocoa
Im currently trying to learn some stuff about encryption, it's algorithms and how it
I'm currently trying to learn ACSL, a precompiled language for Fortran, and have found
I am currently trying to learn about OpenGL ES for the iPhone and following

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.