3

我面临一个与具体类的自动模拟相关AutoFixture以及它如何处理的奇怪问题。AutoMoqCustomization我怀疑我没有很好地使用它,但想知道问题出在哪里。首先是她的一些背景。假设我有一个要测试的课程:

public class IdentityApplicationService
{
    public IdentityApplicationService(
        TenantProvisioningService tenantProvisioningService)
    {
        // guard clause etc.
        _tenantProvisioningService = tenantProvisioningService;
    }
}

及其依赖类TenantProvisioningService(TenantProvisioningService 的依赖在这里不相关,因为它们会被自动模拟,我在测试中并不关心):

public class TenantProvisioningService
{
    readonly IRoleRepository _roleRepository;
    readonly ITenantRepository _tenantRepository;
    readonly IUserRepository _userRepository;

    public TenantProvisioningService(
        ITenantRepository tenantRepository,
        IUserRepository userRepository,
        IRoleRepository roleRepository)
    {
        this._roleRepository = roleRepository;
        this._tenantRepository = tenantRepository;
        this._userRepository = userRepository;
    }
}

这是我的简单测试:

[Fact]
public void ShouldReturnTenantWhenCallingProvisionTenant()
{
    var fixture = new Fixture().Customize(new AutoMoqCustomization());
    var mockTenantProvisioningService =
        fixture.Freeze<Mock<TenantProvisioningService>>();
    var sut = fixture.Create<IdentityApplicationService>();
    var command = new ProvisionTenantCommand(
        "bla",
        "bla SaaS platform",
        "superadmin",
        "superadmin",
        "admin@bla.bla",
        null,
        null,
        null,
        null,
        null,
        null,
        null);
    var tenant = sut.ProvisionTenant(command);

    // some asserts
}

这不起作用,因为当我fixture.Create<IdentityApplicationService>()在其构造函数中调用 then 时,会注入一个具体的 TenantProvisioningService 而不是您可以在mockTenantProvisioningService.Object中找到的代理。

如果我像这样重写测试(注意夹具注入线),一切都会按预期工作(至少由我 :))

[Fact]
public void ShouldReturnTenantWhenCallingProvisionTenant()
{
    var fixture = new Fixture().Customize(new AutoMoqCustomization());
    var mockTenantProvisioningService =
        fixture.Freeze<Mock<TenantProvisioningService>>();
    fixture.Inject(mockTenantProvisioningService.Object);
    var sut = fixture.Create<IdentityApplicationService>();
    var command = new ProvisionTenantCommand(
        "bla",
        "bla SaaS platform",
        "superadmin",
        "superadmin",
        "admin@bla.bla",
        null,
        null,
        null,
        null,
        null,
        null,
        null);
    var tenant = sut.ProvisionTenant(command);

    // some asserts
}

所以我的问题是:我做错了还是它应该是这样?如果不是,请给我解释为什么 AutoFixture 会这样。

4

1 回答 1

6

正如 Mark Seemann指出的那样,这是预期的行为。

以下是更新后的原始帖子中的代码以与当前版本的 AutoFixture 一起使用:

Func<ISpecimenBuilder, bool> concreteFilter = 
    sb => !(sb is MethodInvoker);

var relays = new FilteringRelays(concreteFilter);

var fixture = new Fixture(relays).Customize(
    new AutoMoqCustomization(
        new MockRelay(
            new TrueRequestSpecification())));

FilteringRelays班级保持不变。

于 2013-11-15T15:39:45.537 回答