为方法制作 AutoMoq return 夹具创建的值

Making AutoMoq return Fixture-created values for methods

我想探索是否可以通过将 AutoMoq 创建的所有 Moq 模拟设置为默认 return 夹具创建的值作为方法 return 值来节省时间。

这在进行如下测试时会很有帮助:

[TestMethod]
public void Client_Search_SendsRestRequest()
    var client = fixture.Create<Client>();

    // Could be removed by implementing the mentioned functionality
    Mock.Of(JsonGenerator).Setup(j => j.Search(It.IsAny<string>())).Returns(create("JsonBody")));

    client.Search(fixture.Create("query"));

    Mock.Of(client.RestClient).Verify(c => c.Execute(It.IsAny<RestRequest>()));
    Mock.Of(client.RestClient).Verify(c => c.Execute(It.Is<RestRequest>(r => record(r.Body) == record(client.JsonGenerator.Search(query)))));
}

请注意,生成的值必须缓存在 (?) 代理中,我们需要相同的值 "frozen" 以便检查。此外,使用 Setup 设置模拟应该覆盖创建的值。

那么,我们如何修改 AutoMoq 模拟来做到这一点?

验证它是否有效的简单测试可能是:

[TestMethod]
public void MockMethodsShouldReturnCreatedValues()
{
    Guid.Parse(new Fixture().Create<ITest>().Test());
}

public interface ITest
{
    string Test();
}

绝对可以,只需使用 AutoConfiguredMoqCustomization 而不是 AutoMoqCustomization。模拟将使用夹具为其所有方法、属性和索引器 (*) 生成 returns 值。

属性将被急切求值,而 indexers/methods' return 值将在第一次调用时被求值和缓存。

(*) 此规则有两个例外 - 定制无法自动设置通用方法或使用 ref 参数的方法,如 here 所述。您必须借助 .ReturnsUsingFixture 方法手动设置它们。