开发者

Using dependency injection with Apache Commons IO

开发者 https://www.devze.com 2023-04-09 13:01 出处:网络
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

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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消