gpt4 book ai didi

c# - AutoFixture 设置夹具的声明方式背后的原则是什么?

转载 作者:太空狗 更新时间:2023-10-29 21:05:02 28 4
gpt4 key购买 nike

我之前问过类似的question在 SO 上,我得到了答案。当时,为了方便起见,我机械地应用了答案,但现在我试图了解以声明方式设置夹具的机制是怎样的。

所以,我目前正在查看 Mark Seemann's Dealing With Types Without Public Constructors blog post并将其转换为声明性的。它与我的原始查询非常相似,但我无法让它工作。请注意,给出的代码实际上不是生产代码,这是一个学习练习。

现在,如果有帮助,我已经得到了 imperative code在 GitHub 上,相关代码转载如下:

[Fact]
public static void CanOverrideCtorArgs()
{
var fixture = new Fixture();

var knownText = "This text is not anonymous";
fixture.Register<int, IMyInterface>( i => new FakeMyInterface( i, knownText ) );

var sut = fixture.Create<MyClass>();
}

这是类似于 post 中给出的代码.

因此,我的问题是我应该了解/阅读什么才能将这段命令式代码转换为声明式

最佳答案

去读

有关自定义以及如何打包、混合和混合它们的优秀示例。

主要原则是让您的自定义尽可能细化。

然后,您需要通过以下任一方式将它们提供给处理管道:

  • AutoData - 全局属性的派生属性(即像 Mark 的回答中的 MyTestConventions )
  • CustomizeWith 助手[1] 或类似的
  • 诡计,例如执行 [Freeze( As ... )]

我的实现

自动化这个,我会写:

[Theory, AutoData]
public static void OutOfBandCustomization(
[CustomizeWith( typeof( MyFakerCustomization ) )] MyClass sut )
{
}

使用此自定义:

public class MyFakerCustomization : ICustomization
{
void ICustomization.Customize( IFixture fixture )
{
var knownText = "This text is not anonymous";
fixture.Register<int, IMyInterface>( i =>
new FakeMyInterface( i, knownText ) );
}
}

显然注册一个 string 和/或使用 AutoMoqCustomization 也可能有用。

我的一般助手

[1] CustomizeWith 是这个辅助属性(向 Adam Jasinski 致敬):

[AttributeUsage( AttributeTargets.Parameter, AllowMultiple = true )]
sealed class CustomizeWithAttribute : CustomizeAttribute
{
readonly Type _type;

public CustomizeWithAttribute( Type customizationType )
{
if ( customizationType == null )
throw new ArgumentNullException( "customizationType" );
if ( !typeof( ICustomization ).IsAssignableFrom( customizationType ) )
throw new ArgumentException(
"Type needs to implement ICustomization" );
_type = customizationType;
}

public override ICustomization GetCustomization( ParameterInfo parameter )
{
return (ICustomization)Activator.CreateInstance( _type );
}
}

一边

一个提示:你可以表达

fixture.Register<int, IMyInterface>( i => 
new FakeMyInterface( i, knownText ) );

作为

 fixture.Customize<IMyInterface>(c =>c.FromFactory((int i)=>
new FakeMyInterface(i,knownText)));

也是。虽然这不会让您的情况变得更简单,但它是一种更通用的自定义正在发生的事情的方法。

在内部,注册是[当前]:

fixture.Customize<T>(c => c.FromFactory(creator).OmitAutoProperties());

关于c# - AutoFixture 设置夹具的声明方式背后的原则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16731821/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com