这是否遵循AAA模式?
问题描述:
我有以下测试:这是否遵循AAA模式?
[Test]
public void VerifyThat_WhenHasInterceptorIsCalledWithAComponentModelThatHasTheLogAttribute_TheReturnValueIsTrue()
{
// Arrange
Mock<ComponentModel> mock = /* ... */;
LoggingInterceptorsSelector selector = new LoggingInterceptorsSelector();
// Act & Assert togheter
Assert.That(selector.HasInterceptors(mock.Object), Is.True);
}
是不是有什么毛病统一法&断言?
如果问题不对,应该如何解决这个问题?
编辑:
什么这种测试:
[Test]
[Category("HasInterceptors() Tests")]
public void VerifyThat_WhenHasInterceptorsIsCalledWithANullComponentModel_AnArgumentNullExceptionIsThrown()
{
LoggingModelInterceptorsSelector selector = new LoggingModelInterceptorsSelector();
Assert.That(new TestDelegate(() => selector.HasInterceptors(null)), Throws.TypeOf<ArgumentNullException>());
}
的行为,并断言必须在同一行,以便正确地断言这件事。至少这是我从中理解的。
这个怎么样:
[Test]
[Category("HasInterceptors() Tests")]
public void VerifyThat_WhenHasInterceptorsIsCalledWithANullComponentModel_AnArgumentNullExceptionIsThrown()
{
LoggingModelInterceptorsSelector selector = new LoggingModelInterceptorsSelector();
var testDelegate = new TestDelegate(() => selector.HasInterceptors(null));
Assert.That(testDelegate, Throws.TypeOf<ArgumentNullException>());
}
这是否坚持AAA模式更好?
答
你不应该统一行为并断言。
模式的要点是很容易辨别出不同的部分 - 因此很容易判断你安排测试的位置,然后在行为中调用什么方法,最后是你在声明什么。
混合行为和断言泥泞,这并不是说,对于那些习惯于AAA的人来说,它会让他们吃惊(行为在哪里?)。
更新(以下岗位的编辑):
大多数测试框架允许你指定的预期异常的测试方法(NUnit的和MSTest的使用ExpectedExceptionAttribute
)(这是你的断言)。你仍然应该分开行动。
答
我会做:
[Test]
public void VerifyThat_WhenHasInterceptorIsCalledWithAComponentModelThatHasTheLogAttribute_TheReturnValueIsTrue()
{
// Arrange
Mock<ComponentModel> mock = /* ... */;
LoggingInterceptorsSelector selector = new LoggingInterceptorsSelector();
// Act
var result = selector.HasInterceptors(mock.Object);
// Assert
Assert.That(result, Is.True);
}
AAA,易于阅读。
那么应该做什么?请参阅编辑了解更多详情。 – 2011-05-12 12:26:25
但ExpectedExceptionAttribute会导致测试的Assert阶段从流中消失(或者如果考虑流的属性部分,则首先出现)。 – 2011-05-12 12:46:00
@ the_drow - 但保持清晰度和分离度。这是AAA的动力。清晰和分离,所以你不会失去任何东西。人们习惯于以这种方式进行测试。 – Oded 2011-05-12 12:52:03