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

  • Home
  • SEARCH
  • 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 7681049
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T18:15:14+00:00 2026-05-31T18:15:14+00:00

I’m trying to test a class that takes a factory ( Func<T> ) and

  • 0

I’m trying to test a class that takes a factory (Func<T>) and I’m using Moq and AutoFixture.

What is the best way to setup the “environment” to see if the factory has been used and how many times and what methods have been used on the returned instances?

Currently I’m Mock’ing the T and Injecting a Func<T> that keeps count of all returned Mock instances:

public class SystemUnderTest {
    public SystemUnderTest(Func<IMyClass> c)
    {
        try {
            var c1 = c();
            c1.Name="n1";
            c1.Send();
        }
        catch(Exception){
            var c2 = c();
            c2.Name="n2";
            c2.Send();
        }
    }
}
private Mock<IMyClass> MockFactory()
{
   var m = new Mock<IMyClass>();
   m.SetupProperty(mc=>mc.Name);
   _returnedStubs.Add(m);
   return m;
}  
[Test]
public void TestSomething()
{
    var fixture = new Fixture();
    fixture.Inject(()=>MockFactory().Object)
    var sut = fixture.CreateAnonymous<SystemUnderTest>();
    Assert.That(_returnedStubs.Count,Is.Equal(1));
    _returnedStubs[0].Verify(m=>m.Send(),Times.Exactly(1));
    _returnedStubs[0].Verify(m=>m.Name = "n1");
}

But it feels kinda iffy/ugly to me. And I’m pretty sure that an instance variable in a test class is a dangerous thing

  • 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-05-31T18:15:15+00:00Added an answer on May 31, 2026 at 6:15 pm

    Since AutoFixture is able to create anonymous delegates, when asked to create an anonymous instance of SystemUnderTest, it will also automatically provide an anonymous Func<IMyClass> delegate, which in turn returns an anonymous instance of IMyClass when invoked.

    This means that, given this scenario:

    public class SystemUnderTest
    {
        public SystemUnderTest(Func<IMyClass> c)
        {
            try
            {
                var c1 = c();
                // ...
            }
            catch (Exception)
            {
                var c2 = c();
                // ...
            }
        }
    }
    

    the following code:

    var fixture = new Fixture();
    var sut = fixture.CreateAnonymous<SystemUnderTest>();
    

    will assign the c1 and c2 variables with anonymous instances of IMyClass. Furthermore, if you configure AutoFixture to work as an auto-mocking container, for example using the AutoMoqCustomization, those anonymous instances of IMyClass will also happen to be Moq proxies:

    var fixture = new Fixture();
    fixture.Customize(new AutoMoqCustomization());
    var sut = fixture.CreateAnonymous<SystemUnderTest>();
    

    This information however, although useful, doesn’t really help you in your particular case since you need to get a hold of the mock objects returned by the Func<IMyClass> factory method in your test, in order to configure their behavior and make some assertions on how they’ve been interacted with.

    The best solution, in my opinion, is to change the implementation of the factory method from Func<IMyClass> to an interface. This way you can create a fake factory that returns different mocks of the IMyClass interface when the Create method is invoked multiple times in a sequence:

    So, given this example:

    public interface IFactory<T>
    {
        T Create();
    }
    
    public class SystemUnderTest
    {
        public SystemUnderTest(IFactory<IMyClass> factory)
        {
            try
            {
                var c1 = factory.Create();
                // ...
            }
            catch (Exception)
            {
                var c2 = factory.Create();
                // ...
            }
        }
    }
    

    You can setup your test scenario as follows:

        // Given
        var c1 = new Mock<IMyClass>();
        var c2 = new Mock<IMyClass>();
        // TODO: setup the behavior of the mock objects
        var factory = new Mock<IFactory<IMyClass>>();
        factory.Setup(s => s.Create()).ReturnsInOrder(c1.Object, c2.Object);
    
        // When
        var fixture = new Fixture();
        fixture.Inject(() => factory.Object)
        var sut = fixture.CreateAnonymous<SystemUnderTest>();
    
        // Then
        // TODO: verify the expectations on the mock objects
    

    Note that the ReturnsInOrder is a custom extension method that uses the Callback method in Moq to return different values from a stubbed method when it gets invoked multiple times in a row.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace

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.