AutoFixture and private properties

空扰寡人 提交于 2019-12-23 07:27:24

问题


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();
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/22707369/autofixture-and-private-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!