Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DefaultValueProvider extensibility #1450

Open
eranikid opened this issue Dec 19, 2023 · 0 comments
Open

DefaultValueProvider extensibility #1450

eranikid opened this issue Dec 19, 2023 · 0 comments

Comments

@eranikid
Copy link

Imagine I have

// Oversimplified
interface IContainer<T> {
  T Value { get; set; }
}

Somewhere in my codebase. For unit-testing purposes I would also have a basic hand-mocked version:

class FakeContainer<T> : IContainer<T> {
  public T Value { get; set; }
}

Now I want to be able to do stuff like this:

var mock = new Mock<IHaveIntegerContainer>();
mock.Object.IntegerContainer.Value = 42;
Assert.That(mock.Object.IntegerContainer.Value, Is.EqualTo(42));

Which obviously throws NRE as-is, because IntegerContainer is null by default. If I understand the docs correctly, I can address this issue by implementing a custom DefaultValueProvider as follows:

public class ContainerAwareDefaultValueProvider : DefaultValueProvider {
    protected override object GetDefaultValue(Type type, Mock mock) {
        if (Utils.IsContainerType(type)) {
            return Utils.MakeFakeContainer(type);
        }
        return new object(); // TODO What to return here?
    }
}

I can even make a MockRepository instance in order to reuse this DefaultValueProvider implementation across the whole test suite. But question arises - what should I return in case the condition under the if evaluates to false (e.g. we're trying to instantiate an arbitrary type, unrelated to IContainer<T>)?

  • I can't directly pass control to neither DefaultValueProvider.Empty.GetDefaultValue(type, mock) nor DefaultValueProvider.Mock.GetDefaultValue(type, mock), because the method is protected internal
  • I can't inherit from neither EmptyDefaultValueProvider nor MockDefaultValueProvider and call base.GetDefaultValue(type, mock), because both classes are sealed with internal constructors

Is my only option to duplicate the implementation of one of existing DefaultValueProviders? Or am I missing on the intended way to do what I'm seeking to do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant