سؤال

Can I instruct AutoFixture to fill also private properties, annotated with a specific attribute such as Ninject.Inject, of all classes? The source seems to scan for public properties only: 1. This question provides a solution for specific MyClass with private setter, but not for private property or all classes: 2.

I'm using Moq to mock the services and in the end I'd like to fill the properties with those mocks. The following setup works fine if I expose the MyService dependency as public.

Some example code:

public class MyController {
    [Inject]
    private IMyService MyService { get; set; }

    public void AMethodUsingMyService() {
        MyService.DoSomething();
        // ...
    }

    // ...
}

public class MyService : IMyService {
    public void DoSomething()
    {
        // ...
    }

    // ...
}

public class MyControllerTest {
    [Theory]
    [AutoMoqData]
    public void MyTest(MyController controller) {
        controller.AMethodUsingMyService();
    }
}
هل كانت مفيدة؟

المحلول

AutoFixture doesn't have built-in support for assigning values to non-public fields or properties. This is by design.

AutoFixture is a utility library for unit testing, and unit tests shouldn't directly invoke private members of the SUT.

AutoFixture was originally build as a tool for Test-Driven Development (TDD), and TDD is all about feedback. In the spirit of GOOS, you should listen to your tests. If the tests are hard to write, you should consider your API design. AutoFixture tends to amplify that sort of feedback, so my first reaction is to challenge the motivation for wanting to do this.

Since you're referencing NInject, it looks as though you're using Dependency Injection (DI). However, DI with private Property Injection sounds exotic. Consider making the properties public, or even better, use Constructor Injection instead of Property Injection.

This will enable AutoFixture to automatically work like an Auto-Mocking Container.

However, AutoFixture is a very extensible library, so if you really must do this, it should be possible to write an extension that can write to private properties, but it's not going to be the simplest AutoFixture extension ever written.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top