Mocking a URL in Java

前端 未结 10 1694
臣服心动
臣服心动 2020-12-14 08:16

We have a URL object in one of our Java classes that we want to mock, but it\'s a final class so we cannot. We do not want to go a level above, and mock the InputStream beca

10条回答
  •  一生所求
    2020-12-14 08:45

    I have used a URLHandler that allows me to load a URL from the classpath. So the following

    new URL("resource:///foo").openStream()
    

    would open a file named foo from within the class path. To do this, I use a common utility library and register a handler. To use this handler, you just need to call:

    com.healthmarketscience.common.util.resource.Handler.init();
    

    and the resource URL is now available.

提交回复
热议问题