c#-关于改进BDD / TDD样式的任何建议吗?
作者:互联网
我正在尝试通过我们的单元测试规范进行设置
在场景Y中发生行为X时的SUT规范
鉴于这件事
还有这件事
当我做X …
然后它应该做…
而且它也应该做…
我将“ GivenThat”的每个步骤都包装在“动作…”中,是否有任何反馈说明与“动作”分开是好/坏/还是使“ GivenThat”更清晰的更好方法?
/// <summary>
/// Given a product is setup for injection
/// And Product Image Factory Is Stubbed();
/// And Product Size Is Stubbed();
/// And Drawing Scale Is Stubbed();
/// And Product Type Is Stubbed();
/// </summary>
protected override void GivenThat()
{
base.GivenThat();
Action givenThatAProductIsSetupforInjection = () =>
{
var randomGenerator = new RandomGenerator();
this.Position = randomGenerator.Generate<Point>();
this.Product = new Diffuser
{
Size =
new RectangularProductSize(
2.Inches()),
Position = this.Position,
ProductType =
Dep<IProductType>()
};
};
Action andProductImageFactoryIsStubbed = () => Dep<IProductBitmapImageFactory>().Stub(f => f.GetInstance(Dep<IProductType>())).Return(ExpectedBitmapImage);
Action andProductSizeIsStubbed = () =>
{
Stub<IDisplacementProduct, IProductSize>(p => p.Size);
var productBounds = new ProductBounds(Width.Feet(), Height.Feet());
Dep<IProductSize>().Stub(s => s.Bounds).Return(productBounds);
};
Action andDrawingScaleIsStubbed = () => Dep<IDrawingScale>().Stub(s => s.PixelsPerFoot).Return(PixelsPerFoot);
Action andProductTypeIsStubbed = () => Stub<IDisplacementProduct, IProductType>(p => p.ProductType);
givenThatAProductIsSetupforInjection();
andProductImageFactoryIsStubbed();
andProductSizeIsStubbed();
andDrawingScaleIsStubbed();
andProductTypeIsStubbed();
}
解决方法:
将它们放在单独的方法中,以便您可以在其他给定中组合它们.另外,请使用下划线替换空格(而不是驼峰大小写).另外,创建一个使用动作委托参数的Given_that方法.
protected void Given_that(params Action[] preconditions)
{
foreach (var action in preconditions)
{
action();
}
}
...
protected void a_product_is_set_up_for_injection()
{
...
}
protected void product_image_factory_is_stubbed()
{
...
}
etc...
...
Given_that(a_product_is_set_up_for_injection,
product_image_factory_is_stubbed,
product_size_is_stubbed,
drawing_scale_is_stubbed,
product_type_is_stubbed);
话虽如此,我认为您的前提条件的命名不是BDD.它们本质上是非常技术性的,并不表示业务需要.如果您要告诉非程序员您正在测试什么,您可能不会说“该产品已打针”.您可能会说
Given a displacement product
that is a two inch rectangular diffuser
that has a random position
that has a bitmap
that has a size bounded by feet
that has the expected pixels per foot
现在,您几乎无需重复即可编写“给定”方法:
protected [the type of your test class] Given(params Action given)
{
given();
return this;
}
protected void That(params Action[] preconditions)
{
foreach (var precondition in preconditions)
{
precondition();
}
}
Given(a_displacement_product)
.That(is_a_two_inch_rectangular_diffuser,
has_a_random_position,
has_a_bitmap,
has_a_size_bounded_by_feet,
has_the_expected_pixels_per_foot);
标签:unit-testing,tdd,bdd,c 来源: https://codeday.me/bug/20191210/2098793.html