Jaron Thatcher
Jaron Thatcher

Reputation: 824

How can I "intercept" a method call for a test?

I have a class like so:

class A {

    public static void makeCall() {
        URL url = "www.google.com";
        InputStream result = url.openStream();
        //Do more stuff
    }
}

And I want to write a unit test for it. What I want to happen is sort of "intercept" the call to openStream() so that I can run the static method makeCall() and just return some sort of hard coded JSON back, instead of actually making the call. I haven't been able to figure out how to mock this up, or if it's even possible.

I am looking for the same behavior as Angular's $httpBackend, any ideas or suggestions?

Upvotes: 3

Views: 2087

Answers (1)

UserF40
UserF40

Reputation: 3611

You shouldn't need to mock method member variables. For better design make the url a parameter in the method.

public static void makeCall(URL url){

Then in your test pass in a mock.

This also allows for more flexibility and possible code reuse in the future.

Upvotes: 3

Related Questions