我想将测试方法与其他测试用例一起重用,因为它们共享相同的功能,但使用不同的参数。在下面的代码中,annualSalary
,periodPortion
将会有所不同。
我的问题是,有没有办法重用下面的整个代码块用于其他测试用例,以避免在其他测试方法中重复代码?
int actualTaxResult = IncomeTax.GetIncomeTax(annualSalary, _periodPortion);
//int expectedTaxAmount = 922;
if (actualTaxResult != expectedTaxAmount)
{
Assert.Fail(String.Format("Expected tax amount: {0}, but actual result is {1}", expectedTaxAmount, actualTaxResult));
}
答案 0 :(得分:2)
值得一提的两件事:
例如,使用xUnit,您可以执行以下操作:
[Theory]
[InlineData(100000, 10, 10000)]
[InlineData(150000, 15, 12000)]
[InlineData(210000, 2, 2450)]
public void IncomeTax_Specs(int annualSalary, int periodPortion, int expectedTaxAmount)
{
int actualTaxResult = IncomeTax.GetIncomeTax(annualSalary, periodPortion);
Assert.Equal(actualTaxResult, expectedTaxAmount);
}
答案 1 :(得分:1)
为什么不将该代码块包装在单独的帮助器方法中,并将其用于不同的测试用例,如下所示。但是您可以根据需要更改方法签名,但要传达的是使用辅助方法
private bool CheckData(int annualSalary, int _periodPortion, int expectedTaxAmount)
{
int actualTaxResult = IncomeTax.GetIncomeTax(annualSalary, _periodPortion);
return (actualTaxResult == expectedTaxAmount)
}
然后在你的测试方法中你可以说
if (!CheckData(40000,6,300))
{
Assert.Fail(String.Format("Expected tax amount: {0}, but actual result is {1}", expectedTaxAmount, actualTaxResult));
}
初步回答帮助方法根据您的评论
private void CheckData(int annualSalary, int _periodPortion, int expectedTaxAmount)
{
int actualTaxResult = IncomeTax.GetIncomeTax(annualSalary, _periodPortion);
if (actualTaxResult != expectedTaxAmount)
{
Assert.Fail(String.Format("Expected tax amount: {0}, but actual result is {1}", expectedTaxAmount, actualTaxResult));
}
}