Java TDD – How to Test State of the Object

javatdd

I have a class DataImport
with only two public methods

public void fromStream(InputStream inputStream);
public ImportCommand getImportCommand();

When I test it I send some test data to fromStream method

dataImport.fromStream(some stream with data...)

Only way how to test the result of this method is to get the ImportCommand from getImportCommand and test if this object is in the state according to the input I provided.

But what if ImportCommand has only one method?

public ImportResult execute();

I could test ImportResult (after invoking execute() which would involve some mocks and additional setup) because it has some state exposed. But this way I am testing ImportCommand and the DataImport class in one unit test which does not feel right to me.

But exposing inner state of the classes I am testing or accessing their private fields/methods also is not good thing.

Does this mean that my design is not ok (how should I change it) or is there some way how to solve this situation?

Related: TDD anti-patterns on SO

Best Answer

Don't do any processing in the fromStream() method, just call another method - something like procesStreamResult() that get called whenever something comes in from the stream. This way, you can test procesStreamResult() by calling it with mock objects as arguments and also implement proper error handling and unit testing.

What I'm basically trying to say is: decouple the actual outside dependency (the stream, in your case) from the internal workings of your own code and only test the code you need to test.