How to test IO code in JUnit?

Posted by add on Stack Overflow See other posts from Stack Overflow or by add
Published on 2011-06-21T19:40:42Z Indexed on 2011/06/22 0:23 UTC
Read the original article Hit count: 495

Filed under:
|
|
|
|

I'm want to test two services:

  1. service which builds file name
  2. service which writes some data into file provided by 1st service

In first i'm building some complex file structure (just for example {user}/{date}/{time}/{generatedId}.bin)

In second i'm writing data to the file passed by first service (1st service calls 2nd service)

How can I test both services using mocks without making any real IO interractions?

Just for example:

1st service:

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
}

2nd service:

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) {...}

}

In first case i need to pass FileOutputStream which will create a file (i.e. i can't test 1st service)

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)

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about junit