user3123690
user3123690

Reputation: 1241

Unit testing with complex object dependency

I need to unit test several methods similar to following method. Class ProductItem is petty complex and it is nested. One way to test this method is that I take my time and build an object for ProductItem and pass it to the method, but I feel that it is too tedious. Is there any good way to test it without building the entire object?

public BigDecimal getSubtotal(ProductItem ip) {
    return ip.getTotal().subtract(ip.getTotalTax())
            .subtract(ip.getShipping());
}

Upvotes: 0

Views: 903

Answers (1)

fge
fge

Reputation: 121712

You can use a mocking library such as Mockito. For instance:

final ProductItem mock = mock(ProductItem.class);
when(mock.getTotal()).thenReturn(something);
// same for .getTotalTax(), .getShipping()

Then you can test your .getSubtotal() method:

// Using BigDecimal's .compareTo() for reliable results...
// "0" and "0.0" are not .equals() with BigDecimal!
assertTrue(xxx.getSubtotal(mock).compareTo(expectedResult) == 0);

Note that methods which you do not stub this way will return default values: 0 for primitives, null for objects and false for booleans.

Note 2: requires that ProductItem is not final and that methods you stub are not final either; otherwise you'll have to use PowerMockito and have to write quite some glue as well...

Note 3: works for abstract classes and interfaces as well; you can mock(Comparator.class) for instance

Upvotes: 2

Related Questions