开发者

Does this follow the AAA pattern?

I have the following test:

[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);
}

Is there something wrong with unifying the Act & Assert?

What should be done to remedy this issue if it is wrong?

EDIT:

What about this kind of test:

[Test]
[Category("HasInterceptors() Tests")]
public void VerifyThat_WhenHasInterceptorsIsCalledWithANullComponentModel_AnArgumentNullExceptionIsThrown()
{
    LoggingModelInterceptorsSelector selector = new LoggingModelInterceptorsSelector();

    Assert.That(new TestDelegate(() => selector.HasInterceptors(null)), Throws.TypeOf<ArgumentNullException>());
}

The act and assert must be on the same line in order to assert it correctly. At least that's what I understand from it.

What about this one:

[Test]
[Category("HasInterceptors() Tests")]
pub开发者_运维问答lic void VerifyThat_WhenHasInterceptorsIsCalledWithANullComponentModel_AnArgumentNullExceptionIsThrown()
{
    LoggingModelInterceptorsSelector selector = new LoggingModelInterceptorsSelector();
    var testDelegate = new TestDelegate(() => selector.HasInterceptors(null));
    Assert.That(testDelegate, Throws.TypeOf<ArgumentNullException>());
}

Does this adhere to the AAA pattern better?


I would do:

[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 and easy to read.


You should not unify the act and assert.

The point of the pattern is to easily discern the different parts - so it is very easy to tell where you are arranging the test, then what method is being called in act and finally, what you are asserting on.

Mixing act and assert muddies this, not to say, for those used to AAA it would take them by surprise (where is the act?).


Update (following edit of post):

Most test frameworks allow you to specify an expected exception (nUnit and MSTest use an ExpectedExceptionAttribute) in the test method (that's your assert). You still should act separately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜