Reputation: 513
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());
Upvotes: 6
Views: 2485
Reputation:
It does you no good to have same code in test and in 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
.
Upvotes: 6
Reputation: 2709
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));
}
Upvotes: 3