单元测试-如何正确计算断言的期望值

6

我是单元测试的新手,我想知道如果一个方法在内部调用它自己的公共方法来计算返回值会怎样,像下面这样:

public Integer getTotalBeforeSubscriptionDiscount() {
  return getTotal() + getSubscriptionSavings()
}

我正在为它编写单元测试,我的问题是:在匹配结果和期望值时,是否应该使用特定的整数值,例如

Integer expected = 10;
Integer actual = obj.getTotalBeforeSubscription();
assertEquals(expected, actual);

或者,是否可以在运行时调用公共方法并计算期望值,就像以下:

Integer expected = obj.getTotal() + obj.getSubscriptionSavings();
assertEquals(expected, obj.getTotalBeforeSubscription());
2个回答

6

将相同的代码用于测试和被测试的类是无益的。

如果在getTotal()实现中引入错误,则第二种选项仍会通过,错过了错误。

因此,答案是使用明确的数字,或者至少使用不同的代码,例如expected = expectedTotal + expectedSavings


3

单元测试被视为正在测试的代码的文档。也就是说,通过查看您的测试,应该能够展示代码的目的。

在您的情况下,getTotalBeforeSubscriptionDiscount 方法会将 totalsubscriptionSavings 相加。因此,在您的测试中,最好明确说明这一点。

代码应该像这样:

@Test
public void shouldReturnSumOfTotalAndSubscriptionSavings() {
    Class obj = new ClassA();
    obj.setTotal(10);
    obj.setSubcriptionSavings(12);

    Integer actual = obj.getTotalBeforeSubscription();

    assertThat(actual, is(22));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接