简体   繁体   中英

How to mock Java.net.URL class using EasyMock

As we know URL is a final class so can any one tell me how I can mock that class while writing the test cases using EasyMock.

I am writing the test case for one method which is using URL looking like this.

public String call() {
    //some logics
    URL url=new URL("url name")
}

So how I can mock URL while writing the test case for call method

You cannot use pure EasyMock to mock final classes/methods. However, it can be done with PowerMock extension as explained here .

Or you may wrap the URL into some non-final class which can be mocked:

class MyURL {
    private URL url;
    public MyURL(URL url) {
        this.url = url;
    }

    public URLConnection openConnection() throws IOException {
        return url.openConnection();
    }
// ... etc.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM