Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to test IO code in JUnit?
    text
    copied!<p>I'm want to test two services:</p> <ol> <li>service which builds file name</li> <li>service which writes some data into file provided by 1st service</li> </ol> <p>In first i'm building some complex file structure (just for example <code>{user}/{date}/{time}/{generatedId}.bin</code>)</p> <p>In second i'm writing data to the file passed by first service (1st service calls 2nd service)</p> <p>How can I test both services using mocks without making any real IO interractions?</p> <p>Just for example:</p> <p>1st service:</p> <pre><code>public class DefaultLogService implements LogService { public void log(SomeComplexData data) { serializer.write(new FileOutputStream(buildComplexFileStructure()), data); or serializer.write(buildComplexFileStructure(), data); or serializer.write(new GenericInputEntity(buildComplexFileStructure()), data); } private ComplextDataSerializer serializer; // mocked in tests } </code></pre> <p>2nd service:</p> <pre><code>public class DefaultComplexDataSerializer implements ComplexDataSerializer { void write(InputStream stream, SomeComplexData data) {...} or void write(File file, SomeCompexData data) {...} or void write(GenericInputEntity entity, SomeComplexData data) {...} } </code></pre> <p>In first case i need to pass FileOutputStream which will create a file (i.e. i can't test 1st service)</p> <p>In second case i need to pass File. What can i do in 2nd service test if I need to test data which will be written to specified file? (i can't test 2nd service)</p> <p>In third case i think i need some generic IO object which will wrap File. Maybe there is some ready-to-use solution for this purpose?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload