在NUnit测试中使用Moq验证函数调用时,如何遵循DRY原则
本文关键字:何遵循 原则 DRY 函数调用 验证 测试 NUnit Moq | 更新日期: 2023-09-27 17:57:44
我有几个以下类型的测试,它们验证对对象的函数调用是否会导致对添加到对象中的任何项的相应调用。有没有办法把它抽象成一个函数,或者我试图对此过于枯燥?
[SetUp]
public void InstantiateTesterApp()
{
t = new TesterApp();
mock = new Mock<ITestEquipment>();
t.AddTestEquipment(mock.Object);
}
[Test]
public void OpenEquipmentOpensAddedEquipment()
{
t.OpenEquipment();
mock.Verify(eq => eq.Open());
}
[Test]
public void CloseEquipmentClosesAddedEquipment()
{
t.CloseEquipment();
mock.Verify(eq => eq.Close());
}
对于有许多场景具有类似设置和期望的单元测试套件,我通常会发现使用标准单元测试[Setup]
方法或将其替换为SUT的自定义工厂方法,或者在单元测试类上制作SUT和mocks字段,就像您所做的那样。类似地,对于Assert
和Verifies
,标准的成功和失败预期可以重构为2个标准的辅助方法,例如:
// Standard Setup helper
private void SetupTesterApp(int someReturnParam, bool someTweak = true, ...)
{
mockTestEquipment = new Mock<ITestEquipment>();
mockTestEquipment.Setup(_ => _.SomeMethod()).Returns(someReturnParam);
mockTestEquipment.SetupGet(_ => _.SomeProperty).Returns(someTweak);
t.AddTestEquipment(mockTestEquipment.Object);
}
private void VerifyStandardHappyScenario()
{
Assert.IsFalse(sut.InFaultedStatus);
mockErrorHandler.Verify(_ => _.HandleError(It.IsAny<Exception>()), Times.Never);
... all other standard 'happy scenario' checks
}
... + Similar method for for standard Failure Scenario verifications
这允许每个UT按照以下模式进行干燥:
[Test]
public void OpenEquipmentOpensAddedEquipment()
{
// Standard Arrange
SetupTesterApp(ConstForNormalOperation);
// Test-Specific setups (possibly overriding the above factory setup)
mockTestEquipment.Setup(_ => _.AnotherMethod()).Returns(OverriddenValue);
// Act
Assert.DoesNotThrow(() => t.OpenEquipment());
// Standard Asserts
VerifyStandardHappyScenario();
// Specific Asserts and Verifies to this test
mock.Verify(eq => eq.Open(), Times.Exactly(1));
}