Unit Testing - how to properly calculate expected value for assertion

I am new in unit testing and I was just wondering what if a method internally calls its own public methods to calculate the return value like following:

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

I am writing unit test for it and my question is: Should I use specific integer values for matching the result the result with expectations e.g

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

OR is it allowed to call public methods and calculate expected value at runtime like following:

Integer expected = obj.getTotal() + obj.getSubscriptionSavings();
assertEquals(expected, obj.getTotalBeforeSubscription());

2 answers

  • answered 2018-07-17 19:18 Arkadiy

    It does you no good to have same code in test and the class under test.

    If you introduce an error in getTotal() implementation, your second option would still pass, missing the bug.

    So the answer is, use explicit numbers, or at least different code, such as expected = expectedTotal + expectedSavings.

  • answered 2018-07-18 13:11 Thiru

    Unit tests are considered as documentation for the code that is being tested. Having said, on looking at your test, it should demonstrate what the code is meant for.

    In your case, getTotalBeforeSubscriptionDiscount method, sums up total and subscriptionSavings. So, in your test, it's better to explicitly mention that.

    Code should look something like this:

    public void shouldReturnSumOfTotalAndSubscriptionSavings() {
        Class obj = new ClassA();
        Integer actual = obj.getTotalBeforeSubscription();
        assertThat(actual, is(22));