c# - 使用 Machine.Fakes 和 WithSubject<TSubject> 如何告诉框架在创建主题时使用特定的构造函数参数值

标签 c# mspec machine.fakes

我想告诉 Machine.Fakes 框架在创建主题时为构造函数参数使用特定值

被测对象有如下构造函数

    /// <summary>
    /// Initializes a new instance of the <see cref="CsvFileRepository{TModel}"/> class.
    /// </summary>
    /// <param name="fileService">The file service.</param>
    /// <param name="repositorySettings">The repository settings.</param>
    /// <param name="mappingFunction">The mapping function. The mapping function takes in a line from the CSV file and returns the model for said line.</param>
    public CsvFileRepository(IFileService fileService, IRepositorySettings repositorySettings, Func<string, TModel> mappingFunction)
    {
        this.FileService = fileService;
        this.RepositorySettings = repositorySettings;
        this.MappingFunction = mappingFunction;
    }

我已经创建了一个测试 stub ,如下所示:

public class when_i_pass_a_csv_file_the_results_are_mapped_to_model_objects : WithSubject<CsvFileRepository<StandardOffer>>
{
    Establish context = () => With(new OffersInFile(new[] { OfferTestData.BobsCsvTestData, OfferTestData.JohnsCsvTestData }));

    Because of = () => result = Subject.Get();

    It should_return_the_same_number_of_fruits_as_there_are_in_the_source_repository = () => result.Count().ShouldEqual(2);

    static IEnumerable<IOffer> result;                            
}

但我不确定如何告诉 Machine.Fakes 为 Func mappingFunction 参数使用特定值。

最佳答案

您可以使用 Configure() WithSubject<T> 上的方法:

Establish context = () =>
    Configure(x => x.For<Func<string, StandardOffer>>()
        .Use(input => new StandardOffer(input)));

以这种方式注册的函数优先于自动模拟。

关于c# - 使用 Machine.Fakes 和 WithSubject<TSubject> 如何告诉框架在创建主题时使用特定的构造函数参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9963827/

相关文章:

c# - WPF 网格无法正常拖放

c# - 如何在 TextBlock 和 ProgressBar 中显示进度?

mspec - 如何使用 Machine.Fakes 确保构造函数不会调用本地方法?

C# 数组和属性

asp.net-mvc-2 - 如何在 asp.net mvc 2 中使用 fakeiteasy 伪造用户登录以进行单元测试

unit-testing - 如何在 MSpec 中使用 It 断言输出消息

.net - Appharbor 上的 MSpec

c# - 如何使用 Machine.Fakes (Moq) 模拟 Function<>?

c# - 从 JSON 响应中删除元素