Question

Is it possible to write unit tests for below piece of functionality ?

or,

Is it possible to develop below piece of functionality using TDD ?

public ZipInputStream getZipInputStream(File zipFile) throws FileNotFoundException {
        ZipInputStream zipInputStream = new ZipInputStream(
                new FileInputStream(zipFile));
        return zipInputStream;
}

I know that this question may sounds silly, but as a newbie to TTD, i am not able to find any solution for the above :) .

Was it helpful?

Solution

You've asked two questions in one.

Is it possible to write unit tests for below piece of functionality?

Most people wouldn't consider a test for this functionality to be a "unit test", because it has to interact with the file system. It's therefore more of an integration test than a unit test. However, whether it's possible or not, it's not really a good idea. There's nothing here worth testing. This method doesn't have any logic of its own, so there is no gain in testing it. All you'd be testing is the Java API.

Is it possible to develop below piece of functionality using TDD?

When using TDD, you write code that meets a clear, testable requirement. Something this small is unlikely to have its own requirement. The requirement that leads to this code being written is going to be something to do with processing data that's found in a zip file. So you'll write a method that does a whole lot more than this - preceded of course by writing the test for that method.

However, the third step in the TDD process is refactor. (Remember "red" - "green" - "refactor" - "red" - "green" - "refactor"). You might very well end up writing the method that you've quoted; not by trying to make a test work, but rather by extracting it from a larger method during the refactor step. So the answer is yes, it is possible to develop this functionality, but most likely it would be during the "refactor" step, not during the "green" step.

OTHER TIPS

You're basically combining 2 platform calls (new ZipInputStream() and new FileInputStream()) with no particular logic or conditionals.

It's so simple that I wouldn't even bother testing that one.

In any case, you can't possibly test drive the decorator pattern because it isn't implemented by you. The Decorator is ZipInputStream itself.

You could try to write a test method that receives the input stream decorating a mocked ZipFile that you will provide. Create the mock so that it returns fake ZipEntry instances that you can later verify against the ZipInputStream's getNextEntry() method.

This way you can test that the returned ZipInputStream is really decorating the provided ZipFile (I would suggest a name such as testReturnedZipInputStreamDecoratesProvidedZipFile() or something along those lines...).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top