在AAA单元测试语法中混合断言和动作

时间:2010-09-22 15:10:14

标签: unit-testing arrange-act-assert

混合Assert和Act步骤可以吗? AAA更像是一条指导方针吗?或者我错过了什么?

这是我的测试:

[TestMethod]
public void CancelButtonSelected_DontCancelTwiceThenCancel_DialogCloses()
{
    // Arrange
    IAddAddressForm form = Substitute.For<IAddAddressForm>();
    // Indicate that when Show CancelMessage is called it 
    //  should return cancel twice (saying we want to cancel the cancel)
    //  then it should return ok
    form.ShowCancelMessage().Returns(DialogResult.Cancel, 
         DialogResult.Cancel, DialogResult.OK);

    AddAddressController controller = new AddAddressController(form);
    AddressItem item = TestHelper.CreateAddressBob();

    // Act
    EnterAddressInfo(form, controller, item);
    controller.CancelButtonSelected();
    Assert.IsTrue(form.DialogResult == DialogResult.None);

    controller.CancelButtonSelected();
    Assert.IsTrue(form.DialogResult == DialogResult.None);

    controller.CancelButtonSelected();

    // Assert
    Assert.IsTrue(form.DialogResult == DialogResult.Cancel);
}

所以我称之为方法3次。每次通话后,我都想确保我们没有真正取消对话。然后在第三次调用时,该对话框应该被取消。

这是“合法”使用AAA语法/样式吗?

2 个答案:

答案 0 :(得分:8)

AAA是使您的单元测试更具可读性的指南。在你提供的例子中,我认为你没有实现这个目标。

我认为以下测试使您测试的场景更具可读性。

[TestMethod]
public void CancelButtonSelected_ShouldSetDialogResultToNone_WhenFirstCancelButtonIsSelected()
{
    // Arrange
    IAddAddressForm form = ArrangeFormForCancelButtonSelectedTests();
    AddAddressController controller = ArrangeControllerForCancelButtonSelectedTests();

    // Act
    controller.CancelButtonSelected();

    // Assert
    Assert.IsTrue(form.DialogResult == DialogResult.None);
}

[TestMethod]
public void CancelButtonSelected_ShouldSetDialogResultToNone_WhenSecondCancelButtonIsSelected()
{
    // Arrange
    IAddAddressForm form = ArrangeFormForCancelButtonSelectedTests();
    AddAddressController controller = ArrangeControllerForCancelButtonSelectedTests();

    // Act
    controller.CancelButtonSelected();
    controller.CancelButtonSelected();

    // Assert
    Assert.IsTrue(form.DialogResult == DialogResult.None);

}

[TestMethod]
public void CancelButtonSelected_ShouldSetDialogResultToCancel_WhenThirdCancelButtonIsSelected()
{
    // Arrange
    IAddAddressForm form = ArrangeFormForCancelButtonSelectedTests();
    AddAddressController controller = ArrangeControllerForCancelButtonSelectedTests();

    // Act
    controller.CancelButtonSelected();
    controller.CancelButtonSelected();
    controller.CancelButtonSelected();

    // Assert
    Assert.IsTrue(form.DialogResult == DialogResult.Cancel);
}

答案 1 :(得分:1)

AAA只是让您的单元测试更具可读性的指南。如果你有充分的理由这样做是完全可以的。您使用空格和注释来在一定程度上分离代码中的不同阶段,这很好。在这种情况下,添加解释您正在测试的故事的评论也可能会有所帮助。