Let's say there's a class that processes text, and it gets that text from another class as a buffer. If this buffer class has multiple get methods, like readLine()
, readChar()
, readCharCode()
, how should I choose what method to mock?
Obviously, I can just look at the current implementation of the text processing class and choose to mock the method that is currently being used, but in that case the tests would break if the implementation of the text processing class changed.
Should the whole buffer class be mocked so that the implementation of the text processing class doesn't break the unit tests? This doesn't seem practical.
Should I just mock the method being used, and fix the unit tests whenever the implementation changes?
Edit: I'm using BufferedReader
because it's a simple class that people already understand. Assume that I could be using another class created by me that might be more complex.
This could happen with any testing framework but, using a concrete example in Java (jUnit + Mockito), with a BufferedReader
, here's a text processing class:
public class TextProcessor
{
public String process(BufferedReader bufferedReader)
{
String result = "";
String line;
while ((line = bufferedReader.readLine()) != null)
{
// Process the text line by line.
// (...)
}
return result;
}
}
The unit test using jUnit/Mockito:
@Test
void multipleLineTextTest()
{
TextProcessor textProcessor = new TextProcessor();
BufferedReader bufferedReader = mock(BufferedReader.class);
when(bufferedReader.readLine()).thenReturn("Multiple", "line", "test", null);
assertEquals("test line Multiple", textProcessor.process()); // Assuming the text processor inverted the order of the words.
}
If process()
was changed to use bufferedReader.read()
instead (which reads a single character), the tests would fail, but the implementation could still be correct.
Changing the unit tests as the implementation changes seems to be the way to go, but I still wanted to ask this question to see if there's a better solution, or if I'm looking at it the wrong way.
Thank you.