Max Schmidt
Max Schmidt

Reputation: 7665

Using dependency injection with Apache Commons IO

I have a class 'a' that uses the FileUtils class of Apache Commons IO to copy a directory.

Because I have to write a unit test for class 'a', I need to be able to inject all dependencies to mock them in the test.

But how to inject the FileUtils class? There is no interface and all methods are abstract.

Upvotes: 2

Views: 776

Answers (3)

Bozho
Bozho

Reputation: 597124

All methods of the utility classes are static. You can't mock them (well, you can, with bytecode manipulation, but it's ugly). The proper way to handle that is to provide an abstraction over these utilities. For example implement a FileService, which you declare as a bean, and inject it. Then you can mock its methods.

Upvotes: 6

smp7d
smp7d

Reputation: 5032

You can always wrap it in a file handling layer and create a stub implementation for your unit tests.

Upvotes: 1

flash
flash

Reputation: 6810

You could create your own implementation of FileUtils by extending it OR use a mocking library like jMockit or EasyMock.

Upvotes: 2

Related Questions