当 T 是接口时,如何将 IFixture.Build<T>() 与 AutoMoqCustomization 一起使用? [英] How to use IFixture.Build&lt;T&gt;() with AutoMoqCustomization when T is an interface?

查看:31
本文介绍了当 T 是接口时,如何将 IFixture.Build<T>() 与 AutoMoqCustomization 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些只读属性的接口:

I have an interface with some read-only properties:

interface IItem
{
    string Name { get; }
    // ... more properties
}

使用 Fixture.Create() 方法,我可以使用 AutoMoqCustomization 创建单个模拟接口实例,如下所示:

With Fixture.Create() method I can create a single mocked interface instance using the AutoMoqCustomization like so:

var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization());

var mockedItem = fixture.Create<IItem>();

但是要使用 Fixture.Build().CreateMany() 创建这些接口实例的列表,我不能仅通过执行以下操作来实现:

But to create a list of those interface instances with Fixture.Build().CreateMany(), I cannot do it just by doing the following:

var mockedItems = fixture
    .Build<IItem>()
    .With(x => x.Name, "Abc")
    .CreateMany();

我需要 Build() 的原因是我想为某个属性有一个特定的返回值,而剩下的属性仍然是自动生成的.但不幸的是,根据文档,当使用 Build() 时,灯具上的所有自定义都被绕过了.

The reason that I need Build() is that I want to have a certain return value for a certain property, and leave the rest of the properties to be still auto-generated. But unfortunately, according to the documentation, when using Build() all the customizations on the Fixture is bypassed.

我使用以下版本:AutoFixture 4.8.0、AutoFixture.AutoMoq 4.8.0 和 Moq 4.9.0.

I am using the following versions: AutoFixture 4.8.0, AutoFixture.AutoMoq 4.8.0 and Moq 4.9.0.

是否有一种简单的方法可以实现这一点,而无需定义我自己的 ISpecimenBuilder?

Is there a simple way to achieve this without having to define my own ISpecimenBuilder?

推荐答案

可以从对象中提取出mock并进行配置

The mock can be extracted from the object and configured

var mockedItems = fixture.CreateMany<IItem>(3);

foreach (var item in mockedItems) {
    Mock<IItem> mock = Mock.Get(item);
    mock.Setup(_ => _.Name).Returns("Abc");
}

这篇关于当 T 是接口时,如何将 IFixture.Build<T>() 与 AutoMoqCustomization 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆