Unit Testing - how to properly calculate expected value for assertion

Abdul Fatah :

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());
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:

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

    Integer actual = obj.getTotalBeforeSubscription();

    assertThat(actual, is(22));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113948&siteId=1