0
public interface MessageProducer {
    public void produce(String message);
    public Map<String, Set<String>> getMessagesMapped();
} 

public MessageProducerImpl {
   @Override
   public void produce(String message) {
       //code logic here calls private class methods to manipulate messages
   }

@Override
public Map<String, Set<String>> getMessagesMapped() {
    return map;
}
}

How should one test-drive a scenario like the above and ensure good test coverage when:

  • Entry point produce() is void complying to contract defined by interface and has no return type.
  • other methods are private in the MessageProducerImpl class
  • Not allowed to change interface
M06H
  • 1,675
  • 3
  • 36
  • 76

1 Answers1

1

You do not test the interface, you test the implementation. The interface may be too generic to test.

Even though it is a void method, it should do something. Write to file, update the cache, anything. As it is a void method, it should have a side effect. (if it's not, it can be removed, right?)

So, test the results, since apparently, the side effects are part of the contract (and hence, should be tested).

In your sample code, you have a stateful object (not recommended usually, unless it's a plain value object / DTO), so you can only test it as a whole, since it's state-dependent. (for example, consider it having an extra method which influences the produce() method's logic)

So testing includes both methods at the very least
For your sample code, a sample test:

@Test public void myTest() {
    MessageProducerImpl underTest = new MessageProducerImpl();
    String sampleInputString = ....; // a sample string, from which the expected result is that it's split in 4 keys
    underTest.produce(sampleInputString);
    Map<String, Set<String>> result = underTest.getMessagesMapped();
    assertEquals(4, result.size());
}

Your code coverage tool should then flag it green.

Koos Gadellaa
  • 1,220
  • 7
  • 17
  • In the test class, I'm invoking `produce()` method of the implementation, which builds a map and then the map keys/values are tested? but this would flag red still in the test-coverage as 0% for lines and methods. – M06H Jul 01 '16 at 14:29