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 7526261
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T03:46:58+00:00 2026-05-30T03:46:58+00:00

I encountered a class during my work that looks like this: public class MyObject

  • 0

I encountered a class during my work that looks like this:

public class MyObject
{
  public int? A {get; set;}
  public int? B {get; set;}
  public int? C {get; set;}
  public virtual int? GetSomeValue()
  {
    //simplified behavior:
    return A ?? B ?? C;
  }  
}

The issue is that I have some code that accesses A, B and C and calls the GetSomeValue() method (now, I’d say this is not a good design, but sometimes my hands are tied ;-)). I want to create a mock of this object, which, at the same time, has A, B and C set to some values. So, when I use moq as such:

var m = new Mock<MyObject>() { DefaultValue = DefaultValue.Mock };

lets me setup a result on GetSomeValue() method, but all the properties are set to null (and setting up all of them using Setup() is quite cumbersome, since the real object is a nasty data object and has more properties than in above simplified example).

So on the other hand, using AutoFixture like this:

var fixture = new Fixture();
var anyMyObject = fixture.CreateAnonymous<MyObject>();

Leaves me without the ability to stup a call to GetSomeValue() method.

Is there any way to combine the two, to have anonymous values and the ability to setup call results?

Edit

Based on nemesv’s answer, I derived the following utility method (hope I got it right):

public static Mock<T> AnonymousMock<T>() where T : class
{
  var mock = new Mock<T>();
  fixture.Customize<T>(c => c.FromFactory(() => mock.Object));
  fixture.CreateAnonymous<T>();
  fixture.Customizations.RemoveAt(0);
  return mock;
}
  • 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-30T03:46:59+00:00Added an answer on May 30, 2026 at 3:46 am

    This is actually possible to do with AutoFixture, but it does require a bit of tweaking. The extensibility points are all there, but I admit that in this case, the solution isn’t particularly discoverable.

    It becomes even harder if you want it to work with nested/complex types.

    Given the MyObject class above, as well as this MyParent class:

    public class MyParent
    {
        public MyObject Object { get; set; }
    
        public string Text { get; set; }
    }
    

    these unit tests all pass:

    public class Scenario
    {
        [Fact]
        public void CreateMyObject()
        {
            var fixture = new Fixture().Customize(new MockHybridCustomization());
    
            var actual = fixture.CreateAnonymous<MyObject>();
    
            Assert.NotNull(actual.A);
            Assert.NotNull(actual.B);
            Assert.NotNull(actual.C);
        }
    
        [Fact]
        public void MyObjectIsMock()
        {
            var fixture = new Fixture().Customize(new MockHybridCustomization());
    
            var actual = fixture.CreateAnonymous<MyObject>();
    
            Assert.NotNull(Mock.Get(actual));
        }
    
        [Fact]
        public void CreateMyParent()
        {
            var fixture = new Fixture().Customize(new MockHybridCustomization());
    
            var actual = fixture.CreateAnonymous<MyParent>();
    
            Assert.NotNull(actual.Object);
            Assert.NotNull(actual.Text);
            Assert.NotNull(Mock.Get(actual.Object));
        }
    
        [Fact]
        public void MyParentIsMock()
        {
            var fixture = new Fixture().Customize(new MockHybridCustomization());
    
            var actual = fixture.CreateAnonymous<MyParent>();
    
            Assert.NotNull(Mock.Get(actual));
        }
    }
    

    What’s in MockHybridCustomization? This:

    public class MockHybridCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Customizations.Add(
                new MockPostprocessor(
                    new MethodInvoker(
                        new MockConstructorQuery())));
            fixture.Customizations.Add(
                new Postprocessor(
                    new MockRelay(t =>
                        t == typeof(MyObject) || t == typeof(MyParent)),
                    new AutoExceptMoqPropertiesCommand().Execute,
                    new AnyTypeSpecification()));
        }
    }
    

    The MockPostprocessor, MockConstructorQuery and MockRelay classes are defined in the AutoMoq extension to AutoFixture, so you’ll need to add a reference to this library. However, note that it’s not required to add the AutoMoqCustomization.

    The AutoExceptMoqPropertiesCommand class is also custom-built for the occasion:

    public class AutoExceptMoqPropertiesCommand : AutoPropertiesCommand<object>
    {
        public AutoExceptMoqPropertiesCommand()
            : base(new NoInterceptorsSpecification())
        {
        }
    
        protected override Type GetSpecimenType(object specimen)
        {
            return specimen.GetType();
        }
    
        private class NoInterceptorsSpecification : IRequestSpecification
        {
            public bool IsSatisfiedBy(object request)
            {
                var fi = request as FieldInfo;
                if (fi != null)
                {
                    if (fi.Name == "__interceptors")
                        return false;
                }
    
                return true;
            }
        }
    }
    

    This solution provides a general solution to the question. However, it hasn’t been extensively tested, so I’d love to get feedback on it.

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

Sidebar

Related Questions

I have just encountered this following code: public class TestFinally { public static void
I encountered a PHP class written by a previous employee that is defined like
I encountered a problem with getPath() recently. my code looks something like this: File
I've been doing an Android tutorial and encountered a class with the following: public
I encountered this during object-relational mapping while creating a row mapper (to map a
I am writing a little class and I encountered a problem. This class reads
I'm trying to implement this singleton class. But I encountered this error: 'Singleton::~Singleton': cannot
I'm starting with Python and encountered this weird behaviour (atleast for me): class Parent:
I have difficulties understanding a problem I encountered during instantiation of a QT class
We have encountered a very strange class not found problem in our web app

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.