magulla
magulla

Reputation: 509

Unit Testing Object Converters

How do you test, or do you test at all, classes that convert some other data model/structure into your data model?

interface ToTradeObjectConverter<T> {
    public Trade convertToTrade (T source);
}

public class Trade {
    // here we have ~ 100 fields, like dates, account, currencies, etc.
}

The converter just populates Trade through setters, getting data from another object or parsing a text or XML or whatever.

Would you test such a class? If so, what is a good approach? I don't want to mock (EasyMock) arguments and add 100 lines of "easy mock expect proper getter and setter invoked".

Upvotes: 4

Views: 2994

Answers (1)

Dave Schweisguth
Dave Schweisguth

Reputation: 37617

If these classes are automatically generated, or if they are hand-written but never do anything interesting to the input (they just copy it), AND if you have integration coverage, I wouldn't test them. (I'm coming from a BDD perspective here: make the acceptance/integration test(s) pass first, and then unit-test-drive the rest as necessary.)

If these classes do something interesting, and/or if they don't have integration coverage, test them.

I would definitely not use mocking. These appear to be simple classes which do all their work in memory. I think the secret to testing these classes without too much pain would be to give them all robust .equals methods (if they don't have them already). You can probably generate them. Then your unit tests will be something like

public class ToTradeObjectConverterTest {
  @Test
  public void convertToTradeReturnsTheExpectedObject() {
    TradeSource source = new TradeSource(/* whatever goes here */);
    Trade trade = new ToTradeObjectConverter<TradeSource>().convertToTrade(source);
    Trade expectedTrade = new Trade(/* whatever goes here */);
    assertThat(expectedTrade, equalTo(trade));
  }
}

Upvotes: 3

Related Questions